How to set expire_in in OAUTH 2.0?
configure your oauth configuration changing your Bean TokenServices and setting accessTokenValiditySeconds property :
<bean id="tokenServices"
class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
<property name="accessTokenValiditySeconds" value="1" />
<property name="tokenStore" ref="tokenStore" />
<property name="supportRefreshToken" value="true" />
<property name="clientDetailsService" ref="clientDetails" />
</bean>
Create a custom class of AuthorizationCodeAccessTokenProvider and override the parent
public method obtainAccessToken(OAuth2ProtectedResourceDetails details, AccessTokenRequest request)
In the overridden method of your custom class, call upon the program logic of its parent class:
DefaultOAuth2AccessToken token = super.obtainAccessToken(details, request);
This will return an AccessToken. Now, you just have to manipulate the expired value of that token directly, by providing a timestamp from the past
token.setExpiresIn(int timestamp)
It can be set with a ClientBuilder
obtained from a ClientDetailsServiceConfigurer
.
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.secret("secret")
.authorizedGrantTypes("authorization_code", "refresh_token", "password")
.scopes("app")
.accessTokenValiditySeconds(30);
}
// ... additional configuration
}
or directly on DefaultTokenServices
depending on your need.
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// optionally here you could just get endpoints.getConsumerTokenService()
// and cast to DefaultTokenServices and just set values needed
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(endpoints.getTokenStore());
tokenServices.setSupportRefreshToken(true);
tokenServices.setClientDetailsService(endpoints.getClientDetailsService());
tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
tokenServices.setAccessTokenValiditySeconds(60);
endpoints.tokenServices(tokenServices);
}
}
You can also configure the DefaultTokenServices
in the application.yaml
file.
security:
oauth2:
client:
clientId: client-id
clientSecret: client-secret
authorized-grant-types: authorization_code,refresh_token,password
scope: openid
access-token-validity-seconds: 30