Java Spring Security OAuth2.0 通过token 获取用户信息(ID)
Spring OAuth2.0 通过token 获取用户信息--解密方式
Authentication(身份认证)
通过获取Spring 身份认证(Authentication)来获取用户信息,这种方式必须
①请求头中携带Authorization token
或
②请求参数中携带access_token =token 参数
才能有效获取用户信息
String userId;
//获取身份验证
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication instanceof OAuth2Authentication) {
OAuth2Authentication oAuth2Authentication = (OAuth2Authentication)authentication;
Object details = oAuth2Authentication.getUserAuthentication().getDetails();
if (details == null) {
log.error("获取用户信息失败!");
throw new UserException("获取用户信息失败!");
} else {
try {
//获取用户详细信息
Map<String, ?> userInfo = (Map)details;
userId= userInfo == null ? null : String.valueOf(userInfo.get("user_id"));
} catch (Exception var5) {
log.error(var5.getMessage());
throw new ClassCastException("类型转换异常");
}
}
}
JwtHelper(token解密)
1)那我如果不使用常规传递模式,而使用自定义token参数名、或者其他渠道获取的token;
2)需要使用JwtHelper 进行解密;
示例代码中 使用的请求参数名就是 T,通过T 参数获取token 并且解密
//获取请求request
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//获取token管理服务
BearerTokenExtractor bearerTokenExtractor = new BearerTokenExtractor();
//通过token管理提取token
Authentication extract = bearerTokenExtractor.extract(request);
Object principal = extract == null ? null : extract.getPrincipal() ;
//获取token
String token;
if (Objects.isNull(extract)){
token = request.getParameter("T"); //自定义参数token名称
}else {
token = String.valueOf(extract.getPrincipal());
}
//解析token
Jwt jwt = JwtHelper.decode(token);
String claimsStr = jwt.getClaims();
Map<String, Object> claims = JsonParserFactory.create().parseMap(claimsStr);
String userId = String.valueOf(claims.get("user_id"));