架構:
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