Authentication(身份认证)
通过获取Spring 身份认证(Authentication)来获取用户信息,这种方式必须
①请求头中携带Authorization token
或
②请求参数中携带access_token =token 参数
才能有效获取用户信息文章来源:https://www.toymoban.com/news/detail-616200.html
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 并且解密文章来源地址https://www.toymoban.com/news/detail-616200.html
//获取请求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"));
到了这里,关于Java Spring Security OAuth2.0 通过token 获取用户信息(ID)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!