简体   繁体   English

Spring OAuth2 从访问令牌字符串中提取主体

[英]Spring OAuth2 extract Principal from access token string

I have access token received in controller and I need to extract Principal from string access token.我在 controller 中收到了访问令牌,我需要从字符串访问令牌中提取 Principal。 Without using Authentication in method argument since in this object will be different user.在方法参数中不使用身份验证,因为在此 object 将是不同的用户。 Simple decoding of token should help.令牌的简单解码应该会有所帮助。 Anyone know how to do that from just access token string?任何人都知道如何通过访问令牌字符串来做到这一点? Example例子

@RequestMapping(value = "create", method = RequestMethod.POST)
public ResponseEntity create(Authentication authentication,@RequestParam("access_token") String accessToken) {
    //extract Principal from accessToken variable
}

I don't know why you're sending another user's token in the request, which i find it dangerous cause access token contain sensible information ( credentials ).我不知道您为什么要在请求中发送另一个用户的令牌,我认为这很危险,因为访问令牌包含敏感信息(凭据)。 i advise you to change the way you identify the second user by creating something like action or identification token ( the schema you define will contain the id of the user and the information you want to send ).我建议您通过创建操作或识别令牌之类的东西来更改识别第二个用户的方式(您定义的架构将包含用户的 ID 和您要发送的信息)。

in case you have another phylosophhy that you didn't mention and assuming the access token is a Jwt, you must first validate it, using the algorithm and the private key used to hash it.if it's a valid token, you can access its content.如果你有另一个你没有提到的哲学并假设访问令牌是 Jwt,你必须首先使用算法和用于 hash 的私钥来验证它。如果它是一个有效的令牌,你可以访问它的内容.

@RequestMapping(value = "create", method = RequestMethod.POST)
public ResponseEntity create(Authentication authentication,@RequestParam("access_token") JwtAuthenticationToken accessToken) {
   // validate your accessToken
   // to access the token details
   accessToken.getTokenAttributes().get(A_KEY_IN_YOUR_TOKEN)
}

check this class检查这个class

After some time I manage to get Principal from access token string.一段时间后,我设法从访问令牌字符串中获取了 Principal 。

@Autowired
private TokenStore tokenStore;

@RequestMapping(value = "create", method = RequestMethod.POST)
public ResponseEntity create(Authentication authentication,@RequestParam("access_token") String accessToken) {
    tokenStore.readAuthentication(accessToken).getPrincipal();
}

For my case following approach has worked对于我的情况,以下方法有效

@GetMapping("/token")
@ResponseBody
public String userinfo(@RegisteredOAuth2AuthorizedClient("${YOUR_CLIENT}") OAuth2AuthorizedClient authorizedClient) {
    return authorizedClient.getAccessToken().getTokenValue();
}

Ref 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM