I have implemented REST web services in java spring framework. My application needs to acquire an Access Token in order to in order to make other URL requests. I would like to cache the token so I can reuse it until it expires. For now, I'm using a field to store the token but would there be another way using a spring-security class ?
This is how I acquire the accesToken:
@Bean
private OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails() {
ClientCredentialsResourceDetails details = new
ClientCredentialsResourceDetails();
details.setClientId(clientId);
details.setClientSecret(clientSecret);
accessTokenUrl = BackEndUrl + "/oauth2/token";
details.setAccessTokenUri(accessTokenUrl);
return details;
}
@Bean
private OAuth2RestTemplate createRestTemplate(OAuth2ClientContext clientContext) {
return new OAuth2RestTemplate(oAuth2ProtectedResourceDetails(), clientContext);
}
@Override
public ResponseEntity<String> service() {
// Token recovery if no token has been created or if the token expiration time is exceeded
if (this.strToken == null || this.tokenLimitTime.isBeforeNow()) {
OAuth2ClientContext context = new DefaultOAuth2ClientContext();
OAuth2RestTemplate restTemplate = createRestTemplate(context);
OAuth2AccessToken token = restTemplate.getAccessToken();
if (token != null) {
this.strToken = token.getValue();
this.tokenLimitTime = DateTime.now().plusSeconds(token.getExpiresIn());
}
}
Getting the Access TokenUsing the Authorization Code received from the resource server we can get the access token. As can be seen the authorization code is received as a request parameter. And the resource server is trying to contact the client application using the redirect uri.
It's relatively expensive to get an OAuth access token, because it requires an HTTP request to the token endpoint. Therefore, it's good to cache tokens whenever possible.
Before making a request to the resource server, first check if the token has already expired or is about to expire. If so, request a new token. Finally, make the request to the resource server. Save the token and expiration time in memory, and have a timer which triggers a token refresh some interval before expiry.
It depends on which token store you are using. For example if you are using InMemoryTokenStore
or JDBCTOkenStore
there are API provided to access token using username or using client Id (i.e public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName)
or public Collection<OAuth2AccessToken> findTokensByClientId(String clientId)
).
If you are using JwtTokenStore there is ApprovalStore
mechanism.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With