Authentication(身份認證)
通過獲取Spring 身份認證(Authentication)來獲取用戶信息,這種方式必須
①請求頭中攜帶Authorization token
或
②請求參數(shù)中攜帶access_token =token 參數(shù)
才能有效獲取用戶信息文章來源:http://www.zghlxwxcb.cn/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("類型轉(zhuǎn)換異常");
}
}
}
JwtHelper(token解密)
1)那我如果不使用常規(guī)傳遞模式,而使用自定義token參數(shù)名、或者其他渠道獲取的token;
2)需要使用JwtHelper 進行解密;
示例代碼中 使用的請求參數(shù)名就是 T,通過T 參數(shù)獲取token 并且解密文章來源地址http://www.zghlxwxcb.cn/news/detail-616200.html
//獲取請求request
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//獲取token管理服務(wù)
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"); //自定義參數(shù)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"));
到了這里,關(guān)于Java Spring Security OAuth2.0 通過token 獲取用戶信息(ID)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!