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

posted @ 2020-05-21 10:52  欺天大剩  阅读(1562)  评论(0)    收藏  举报