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存储,可能是因为线程池线程重复利用。也可能是别的问题。。。
推荐文章: