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

时间:2018-05-13 08:47:57

标签: spring spring-security

在我的WebSecurityConfigurerAdapter我有这个:

@Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
    DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
    daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
    daoAuthenticationProvider.setUserDetailsService(this.userDetailsService);
    return daoAuthenticationProvider;
}

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

}

但是,我无法使用

获取AppUserDetails implements UserDetails个对象
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// Throws exception because the principal is a String
AppUserDetails appUserDetails = (AppUserDetails) authentication.getPrincipal();

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

我试过了

SecurityContextHolder.getContext().getAuthentication().getDetails()

但这会返回OAuth2AuthenticationDetails,而不是我希望的UserDetails

尝试this也不会工作。返回的details对象为null

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

Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();

Object details = userAuthentication.getDetails();

0 个答案:

没有答案