ejain
ejain

Reputation: 3614

Bypass @Cacheable for (un)authenticated requests

Can Spring's caching framework be made aware of the authentication status of the request context, or is it easier to roll your own caching solution?

Upvotes: 1

Views: 583

Answers (1)

Stephane Nicoll
Stephane Nicoll

Reputation: 33091

Regardless of the fact I find the use case super weird, you can condition caching for pretty much anything that works with SpEL. And since you can call any method you want with SpEL, you're good to go.

I realized that it is harder than it should but the following works. First create a static method that does your check (you can use the SecurityContextHolder for that)

public class SecurityChecker {

    public static boolean isSecured() {
        // Whatever
        return SecurityContextHolder.getContext().getAuthentication() != null;
    }
}

Then in your annotated method, specify the following (assuming myCache should be affected):

@Cacheable(cacheNames = "myCache", condition = "T(com.example.SecurityChecker).isSecured()")
public Foo doIt(String key) { ... }

There's two problems currently:

  1. You can't create a meta-annotation to avoid repeating the condition attribute over and over again (see SPR-13475)
  2. The SpEL setup does not allow you to easily call a method on a bean (which would be nicer than calling a static method). I've just created SPR-13812 for that

Upvotes: 2

Related Questions