Hej,
Nowy dzień, nowy problem. Otóż próbuję odebrać w kotrollerze mojego customowego principala obecnie zalogowanego usera poprzez :
@AuthenticationPrincipal UserPrincipal userPrincipal
Problem w tym, że ten principal jest nullem.. ale kiedy już wyciągne usera z conextu poprzez
SecurityContextHolder.getContext().getAuthentication();
To widzę, że są tam dane użytkownika. Nie rozumiem co robie źlę, albo czego mi brakuję żeby korzystać z @AuthenticationPrincipal.
Mój customowy principal wygląda tak:
@Getter
@AllArgsConstructor
public class UserPrincipal implements UserDetails {
private Long id;
private String username;
private String password;
private Collection<? extends GrantedAuthority> authorities;
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
W konfiguracji security mam adnotację @EnableWebSecurity oraz korzystam z customowego UserServiceDetails który implementuje UserDetailsService , a metoda ładująca usera wygląda tak:
@Override
@Transactional
public UserPrincipal loadUserByUsername(String username) {
User user = userRepository.findByUsername(username).orElseThrow(() -> new UserNotFoundException(username));
Set<GrantedAuthority> authorities = user.getRoles().stream()
.map(role -> new SimpleGrantedAuthority(role.getName()))
.collect(Collectors.toSet());
return new UserPrincipal(
user.getId(),
user.getUsername(),
user.getPassword(),
authorities);
}
Mam oczywiście napisany filtr który sprawdza token JWT, oraz ładuje usera do contextu poprzez
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
Prosiłbym o poradę, czy co mogę robić źle. Ewentualnie czy powinienem jakoś inaczej to zrealizować, może w inny sposób operować na tym customowym obiekcie principala ? @Shalom @jarekr000000 @Charles_Ray
Shalom