In my WebSecurityConfigurerAdapter
I have this:
@Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
daoAuthenticationProvider.setUserDetailsService(this.userDetailsService);
return daoAuthenticationProvider;
}
and the following in the UserDetailsService
:
@Service
public class AppUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
AppUserEntity appUserEntity = this.appUserRepository.findByUsername(username).orElseThrow(() ->
new ResourceNotFoundException("Current user not found."));
return new AppUserDetails(appUserEntity);
}
}
However, I cannot fetch my AppUserDetails implements UserDetails
object with
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// Throws exception because the principal is a String
AppUserDetails appUserDetails = (AppUserDetails) authentication.getPrincipal();
because authentication.getPrincipal()
always returns just a String
(in this case the user's username). However, I expected it to return a AppUserDetails
. Why is this not the case and how can I change this?
I have tried
SecurityContextHolder.getContext().getAuthentication().getDetails()
but this returns OAuth2AuthenticationDetails
and not the UserDetails
I was hoping for.
Trying this won't work either. The returned details
object is null
.
OAuth2Authentication oAuth2Authentication =
(OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();
Object details = userAuthentication.getDetails();