8

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());
        }
    }
ortizbje
  • 138
  • 2
  • 7

1 Answers1

1

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.

hiren
  • 1,742
  • 13
  • 20
  • 4
    These stores appear to be for use in a Server that is OAuth protected for keeping track of tokens that have been handed out. I think the original question is in reference to how to cache tokens on the client. – KC Baltz Mar 06 '18 at 21:03