简体   繁体   English

oauth2自动刷新令牌

[英]oauth2 auto refresh token

I have a spring boot controller, that invokes a service on wso2. 我有一个Spring Boot控制器,该控制器在wso2上调用服务。 (sends an identity and receives a token for further communication). (发送身份并接收令牌以进行进一步的通信)。 I am looking for a way to auto-refresh the token on the spring boot side (because the invocation of the service on wso2 is not done by a browser, but rather by another service). 我正在寻找一种在Spring Boot端自动刷新令牌的方法(因为wso2上服务的调用不是由浏览器完成,而是由另一个服务完成)。 So, on the spring boot side, how can I achieve that? 那么,在弹簧靴方面,我该如何实现呢? I understand that I should check the expiration date of the access_token and use the refresh_token to receive a new access_token, but is there some library that does that or do I have to code this logic myself? 我知道我应该检查access_token的到期日期并使用refresh_token来接收新的access_token,但是是否有一些库可以这样做或者我必须自己编写此逻辑? Also, when running my app on multiple instances of spring boot, how do I prevent the token being refreshed from one instance and invalidating the token on another instance, using the same token? 此外,当在多个Spring Boot实例上运行我的应用程序时,如何防止使用同一令牌从一个实例刷新令牌并使另一个实例上的令牌无效?

OAuth2 provides five grants for acquiring the access token. OAuth2提供了五种授权来获取访问令牌。 One of them is the refresh token grant which is used to obtain a new access token after the client has been authorized for access and the token already expires. 其中之一是刷新令牌授予,该刷新令牌授予用于在客户端被授权访问并且令牌已经过期之后获取新的访问令牌。 In the refresh token grant, the client sends a POST request to the authorization server with the following parameters: 在刷新令牌授予中,客户端使用以下参数将POST请求发送到授权服务器:

grant_type=refresh_token&client_id=your_client_id&client_secret=your_client_secret &refresh_token=your_refresh_token_from_the_first_grant

The auth url should be same the first time you obtain the token. 首次获取令牌时,身份验证网址应相同。 For auto-refreshing the token, you can catch for HttpClientErrorException when you access the resource server and check if the status code is HttpStatus.UNAUTHORIZED . 对于自动刷新令牌,你可以捕捉为HttpClientErrorException当您访问的资源服务器,并检查状态代码为HttpStatus.UNAUTHORIZED If it is, then send request for new token. 如果是,则发送新令牌请求。

try {
    response = getRestTemplate().exchange...
} catch (HttpClientErrorException e) {
    if (e.getStatusCode().equals(HttpStatus.UNAUTHORIZED))
        //code to refresh the token or throw custom exception...
}catch (Exception e) {
    //
}

For multiple instances of the client, this might help you: Spring Oauth2 - multiple tokens per client id 对于客户端的多个实例,这可能会帮助您: Spring Oauth2-每个客户端ID多个令牌

I have not verified it but essentially it uses the scope in the post parameter to generate a different token for the same client_id. 我尚未验证它,但实际上它使用了post参数中的作用域为同一client_id生成了一个不同的令牌。

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

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