springsecurity oauth2在资源服务器获取令牌信息
【学习笔记,代码自己敲,思想非原创】
前提:认证服务器AuthorizationConfig中使用jwt,并可以成功签发令牌,携带Bearer令牌访问资源服务器。
- 第一种-直接解析请求头令牌。
/**
* CustomerJwt是自定义的类,用来保存用户信息
* SignedJWT和JWTClaimsSet来自nimbus-jose-jwt
*/
public static CustomerJwt getJwtClaimsFromHeader(HttpServletRequest request) {
if (request == null) {
return null;
}
String authorization = request.getHeader("Authorization");
if (StringUtils.isBlank(authorization) || !authorization.contains("Bearer")) {
return null;
}
String token = authorization.substring(7);
try {
SignedJWT parse = SignedJWT.parse(token);
JWTClaimsSet jwtClaimsSet = parse.getJWTClaimsSet();
CustomerJwt customerJwt = new CustomerJwt();
customerJwt.setId(jwtClaimsSet.getClaim("user_id").toString());
customerJwt.setUsername(jwtClaimsSet.getClaim("user_name").toString());
return customerJwt;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
- 第二种-springsecurity-oauth2自带参数方法
@Component
public class CustomerTokenConverter {
/**
* 一下的依赖均来自 spring-cloud-starter-oauth2
*/
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Autowired
private TokenStore tokenStore;
/**
* @description 获取用户信息,从Authentication中读取令牌并解析出用户信息
*/
public Map<String, Object> getCustomer(Authentication authentication) {
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(details.getTokenValue());
return oAuth2AccessToken.getAdditionalInformation();
}
}