Reputation: 61
I have an authorisation server and multiple resource servers with OAuth2. All are implemented using Spring Security OAuth2. I have also front end clients which uses Authorization code flow for token generation.
My case is, if the refresh token validity is 2 hrs and access token's is 1 hr. There is no problem in getting the tokens at first(both tokens are new. After 1 hr, access token is expired. Now assume the app retries for a new access token using existing refresh token only after another 30 minutes (1.5 hrs passed) and a new access token is generated with validity of 1 hr which is extra 30 mins than the refresh token. In front ends, i have stored tokens in cookies and refresh token got deleted after its 30 mins. When i try to fetch token freshly again using auth code flow, spring oauth2 server returns the same expired refresh token and the active access token. My app enters in a confused state that whether the user is authorised or not as it only has access token even after several retries.
Is it possible to generate the access token with expiry time always less than or equal to refresh token?
Upvotes: 3
Views: 6860
Reputation: 61
I have handled it in Token Enhancer. I just get the newly generated access token's expiry time and existing refresh token's expiry time. If the access token's expiry time is greater than refresh token's then will update the access token's expiry time to refresh token's expiry time. Below is my code sample.
public class CustomTokenEnhancer implements TokenEnhancer {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
ExpiringOAuth2RefreshToken refreshToken = ((ExpiringOAuth2RefreshToken)accessToken.getRefreshToken());
long refreshTokenExpiresIn = ((ExpiringOAuth2RefreshToken)accessToken.getRefreshToken()).getExpiration().getTime();
long accessTokenExpiresIn = accessToken.getExpiration().getTime();
LOGGER.info("RT {} and AT {}", refreshTokenExpiresIn, accessTokenExpiresIn);
if(accessTokenExpiresIn > refreshTokenExpiresIn) {
((DefaultOAuth2AccessToken) accessToken).setExpiration(refreshToken.getExpiration());
}
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);
return accessToken;
}
}
Here's how to set TokenEnhancer in configuration:
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration implements AuthorizationServerConfigurer {
@Bean
public TokenEnhancer tokenEnhancer() {
return new CustomTokenEnhancer();
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenEnhancer(tokenEnhancer());
}
}
Upvotes: 0