SpringCloud + OAuth2 + Redis 微服务并发下获取用户,用户数据错乱


架构:
spring cloud + oauth2 + redis
问题
各微服务之间通过 spring security 获取当前登录人用户信息时,低概率发生用户获取到另一个用户数据。
(用户数据由 oauth 微服务存储到 redis 中)

 

...
public static synchronized LoginAppUser getLoginAppUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication instanceof OAuth2Authentication) {
OAuth2Authentication oAuth2Auth = (OAuth2Authentication) authentication;
authentication = oAuth2Auth.getUserAuthentication();

if (authentication instanceof UsernamePasswordAuthenticationToken) {
UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication;
Object principal = authentication.getPrincipal();
if (principal instanceof User) {
return (User) principal;
}

Map map = (Map) authenticationToken.getDetails();
map = (Map) map.get("principal");

return JSONObject.parseObject(JSONObject.toJSONString(map), LoginAppUser.class);
}
}
SecurityContext 默认是通过ThreadLocal存储,可能是因为线程池线程重复利用。也可能是别的问题。。。

————————————————
原文作者:LHY_HT
转自链接:https://learnku.com/spring/t/37246


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM