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
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);
}
}
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