Is there a way with Spring Security to cache token introspection result?

Viewed 4385

I have a Spring boot REST API protected by Keycloak with Spring Security.

I can't find if there is a way to prevent token introspection on every request (i.e. caching introspection result for a short period). Everytime I hit the API, token is checked upon Keycloak and this is not great for performance :(

Thanks for any advice.

1 Answers

This is sort of the tradeoff that you make when you use opaque tokens (which require introspection).

With opaque tokens:

  • OAuth 2.0 Clients can't see the contents
  • Authorization Servers can revoke the token at any time

The tradeoff is that you need to check with the Authorization Server on every request to make sure the token hasn't been invalidated.

With JWT:

  • OAuth 2.0 Clients may inspect the contents of the token
  • The JWT carries its own expiry information

What you get in exchange for the performance benefit of JWT is that it can't be invalidated, only expired.

So, this wasn't your question precisely, but you asked about performance, and JWT is a very common way to address the performance hit of opaque tokens.

You might also ask yourself if you need the additional security benefits of opaque tokens for every path in your application. Could you use JWT for some paths and check with the authorization server for higher-security paths?

Anyway, you asked about caching. Yes, Spring Boot publishes an instance of OpaqueTokenIntrospector for you, which you can override with one that caches:

@Component
public class CachingOpaqueTokenIntrospector
        implements OpaqueTokenIntrospector {

    private final NimbusOpaqueTokenIntrospector introspector = 
        // ... construct

    @Override
    public OAuth2AuthenticatedPrincipal introspect(String token) {
        // call delegate introspector and cache        
    }
}

You could use the @Cacheable annotation on the introspect method, for example.

Related