首页 > 解决方案 > authentication.getPrincipal() 始终是 String 而不是 UserDetails

问题描述

在我的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我希望的。


尝试这个也行不通。返回的details对象是null

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

Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();

Object details = userAuthentication.getDetails();

标签: springspring-security

解决方案


推荐阅读