authentication.getPrincipal()始终是String而不是UserDetails

dis*_*ame 5 spring spring-security

在我WebSecurityConfigurerAdapter有这个:

@Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
    DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
    daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
    daoAuthenticationProvider.setUserDetailsService(this.userDetailsService);
    return daoAuthenticationProvider;
}
Run Code Online (Sandbox Code Playgroud)

以及以下内容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);
    }

}
Run Code Online (Sandbox Code Playgroud)

但是,我无法AppUserDetails implements UserDetails使用

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// Throws exception because the principal is a String
AppUserDetails appUserDetails = (AppUserDetails) authentication.getPrincipal();
Run Code Online (Sandbox Code Playgroud)

因为authentication.getPrincipal()总是返回一个String(在这种情况下为用户的用户名)。但是,我希望它返回一个AppUserDetails。为什么不是这种情况,我该如何更改?


我试过了

SecurityContextHolder.getContext().getAuthentication().getDetails()
Run Code Online (Sandbox Code Playgroud)

但这又回来了,OAuth2AuthenticationDetails而不是UserDetails我所希望的。


尝试此操作也不起作用。返回的details对象是null

OAuth2Authentication oAuth2Authentication =
                (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();

Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();

Object details = userAuthentication.getDetails();
Run Code Online (Sandbox Code Playgroud)