I am using OAuth 2.0
with spring for token generation and I want to set expire_in
manually so token can expire as per my criteria. Any one help me?
This is my response:
{ access_token: "c7a6cb95-1506-40e7-87d1-ddef0a239f64" token_type: "bearer" expires_in: 43199 scope: "read" }
This can be done using the following steps: convert expires_in to an expire time (epoch, RFC-3339/ISO-8601 datetime, etc.) store the expire time. on each resource request, check the current time against the expire time and make a token refresh request before the resource request if the access_token has expired.
By default, access tokens are valid for 60 days and programmatic refresh tokens are valid for a year.
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); } }
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>
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