I have a spring boot controller, that invokes a service on 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). 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? 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?
1 Answers
OAuth2 provides five grants for acquiring the access token. 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:
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
. 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
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.

- 6,787
- 10
- 46
- 87