在我的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();