Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define multiple TokenStore(s) in Spring secuirty OAUTH

I have a Spring Security AuthorizationServerConfigurerAdapter configuration which is supporting password and refresh_token grant types.

clients
        .inMemory()
        .authorizedGrantTypes("password", "refresh_token")
        ...;

The TokenStore i am using is JwtTokenStore, thus the refresh_token and access_token are generated as JWT as i am using the DefaultTokenServices

The question is how can i have the refresh_token generated and managed by JdbcTokenStore while the access_token still get generated and managed by JwtTokenStore?

I have thought about extending DefaultTokenServices or implementing AuthorizationServerTokenServices but i'm not sure if there is not any other way offered by the default spring-secuirty config.

Thanks!

like image 286
mgalala Avatar asked Mar 14 '26 10:03

mgalala


1 Answers

One way, to achieve stored tokens (both access token and refresh token) and have JWT encoded tokens at the same time, is provide token store with tokenEnhancer of type JwtAccessTokenConverter.

@Bean
protected TokenStore tokenStore() {
    return new InMemoryTokenStore();
}

@Bean
protected JwtAccessTokenConverter jwtTokenEnhancer() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setSigningKey(privateKey);
    converter.setVerifierKey(publicKey);
    return converter;
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory().withClient("client_trusted")//...
    ;
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.tokenStore(tokenStore())
        .tokenEnhancer(jwtTokenEnhancer()) // <- tokens are encoded in JWT
        .authenticationManager(authenticationManager)
        .userDetailsService(userDetailsService);
    }

With this approach you can easily revoke (or remove) refresh_token. So authorization server will not provide new access token in next refreshing token request. And information in JWT stays self contained and resource server can work without interaction with authorization server.

@Autowired
protected TokenStore tokenStore;

@RequestMapping(method = RequestMethod.POST, value = "/revoke")
public void revokeToken(@RequestParam String token) {
    ((InMemoryTokenStore)tokenStore).removeRefreshToken(token);
}

Here is complete example of authorization and resource server with js client: https://github.com/pufface/spring-oauth-jwt-demo

like image 112
pufface Avatar answered Mar 15 '26 23:03

pufface



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!