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());
}
}