spring-boot - How to update data on Principal object on Spring Boot
问题描述
I'm building a REST API with Spring Boot and OAuth2 and I'm facing with troubles when trying to update the Principal object on a session. I need to do this when updating the user because some relations on the database could change and I think it's not a good option checking the user on the database for getting the values on each request.
I read a lot of posts telling that solution is only adding the new context to a SecurityContextHolder, like this:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
CustomUserDetails u = (CustomUserDetails)authentication.getPrincipal();
//Change here some details from user and update the database
SecurityContextHolder.getContext().setAuthentication(authentication);
But in my case, it doesn't work, if I make a request with the same access token, the Principal object is returning always the old values.
--- EDIT ---
My security config class:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService customUserDetailsService;
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService);
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
And my CustomUserDetailService class:
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Resource
public MyUserRepository usersRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<AppUser> usersOptional = usersRepository.findByEmail(username);
usersOptional.
orElseThrow(() -> new UsernameNotFoundException(username));
return usersOptional
.map(CustomUserDetails::new)
.get();
}
}
解决方案
好的,所以最后我决定正如@r4phG 所说,使当前令牌过期并使用刷新令牌来获取新令牌,从而强制检索更新的用户。
推荐阅读
- javascript - 创建键盘快捷键来更改足球/足球追踪器的颜色?
- fonts - 更改 GIMP 中选定文本的字体
- http-headers - 如何为 NuxtJS 的 SSR 服务器设置自定义响应头?
- solidity - 类型错误:标识符不是合同
- javascript - Bootstrap 5 > 在较小的设备上扩展时更改导航栏的样式
- visual-studio-code - 自动化 VSCode 项目设置
- r - 是否可以并行使用 e1071 调整随机森林?
- java - Webclient 200 状态代码在 responseBody 中失败
- excel - 尝试选择范围内的第一个空单元格
- java - 如何点击href标签?