Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot OAuth - Multiple Access Tokens for same user

Spring-OAuth inserts multiple records in the access_token table when the same user logs in from different devices. What should be done to prevent Spring creating multiple access tokens. A user should be able to login from several devices at the same time.

Using 2.0.3.RELEASE

like image 641
i_raqz Avatar asked Oct 20 '25 03:10

i_raqz


1 Answers

Just for a workaround, and to handle multiple instances of the service. Just get the token first, and if it is found return it, else then create it.

public class OAuthTokenServices extends DefaultTokenServices {
    @Override
    public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {
        OAuth2AccessToken token = super.getAccessToken(authentication);
        try {
            if (Objects.isNull(token) || token.isExpired()) {
                return super.createAccessToken(authentication);
            }
        } catch (DuplicateKeyException dke) {
            log.info("Duplicate key found. Lets get it instead.");
            token = super.getAccessToken(authentication);
            log.info("We got the token. {}", token);
            return token;
        } catch (Exception ex) {
            log.info(String.format("Exception while creating access token %s", ex));
        }
        return token;
    }
}

Then register it:

public class OAuthAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    DefaultTokenServices tokenServices;

    @Autowired
    private TokenStore tokenStore;

    @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        OAuthTokenServices tokenService = new OAuthTokenServices();
        tokenService.setTokenStore(tokenStore);
        tokenService.setSupportRefreshToken(true);
        return tokenService;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.tokenServices(tokenServices);
    }

}
like image 126
Syakur Rahman Avatar answered Oct 21 '25 15:10

Syakur Rahman