spring - 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();
解决方案
推荐阅读
- c++ - 如何使用 MinGW 将静态 GLEW 库链接到 CMake 项目?
- python - 在 Python 中并行化函数调用
- google-cloud-platform - 参数从 rest api 传递到数据流作业时出错 - 云函数
- c# - C#:是否有 IList 的 HashSet 类比?
- json - 来自 Openweathermap API 的 Swift 天气数据?
- python - 我的土壤湿度传感器没有从我的 ESP32 读取数据
- python - 绘制 Pandas 系列的 CDF,索引为 x 轴
- java - @Value 和 @Autowired 上的 NPE
- ios - 如何在 ios swift 的 twilio 聊天推送通知有效负载中添加额外参数
- typescript - 如果我导入文件,TypeScript 找不到在类型声明中声明的变量