我有3个不同的客户端,分别是移动、网络、物联网。我正在使用grant_type = password并获取accessToken。我收到来自所有客户端的请求GET /access/resource。我想根据它们的客户端ID对它们进行不同的处理。我知道使用client_id的/oauth/check_token响应,但如何在资源服务器中提取它
发布于 2020-04-06 01:43:39
使用JWT,当授权服务器创建token时,默认的AccessTokenConverter实现DefaultAccessTokenConverter的convertAccessToken方法做:令牌的"response.put(this.clientIdAttribute, clientToken.getClientId());"也包括客户端id。上面提到的response只是一个哈希图,它将被转换成JWT。
当您的资源服务器在GET /access/resource上被访问时
@RequestMapping("/access/resource")
public @ResponseBody Map<String,Object> getRes() throws IOException {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
ObjectMapper objMapper = new ObjectMapper();
Map<String,Object> map = objMapper.convertValue(auth.getDetails(),Map.class);
Jwt jwt = JwtHelper.decode((String) map.get("tokenValue"));
Map<String,Object> claims = objMapper.readValue(jwt.getClaims(),Map.class);
// This is what you want
String clnt_id = (String) claims.get("client_id"); <<------- here
// your logic here based on clnt_id
// ex: if(clnt_id.equals("Specific client"){}
...
return Collections.emptyMap();;
}或
OAuth2Request还包括已解析的客户端id:
Authentication auth =
SecurityContextHolder.getContext().getAuthentication();
String cliend_id = ((OAuth2Authentication) auth).getOAuth2Request().getClientId()即使没有使用JWT,这个选项也可以应用,因为Oauth2request总是存在的。
看这里可以更好地理解:

https://stackoverflow.com/questions/61038764
复制相似问题