Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 39 ยท Authorization and Method Security

The AuthorizationManager API and Custom Rules

Learn how AuthorizationManager powers URL and method security, write a custom manager for IP, time or tenant rules, and combine managers with AND, OR and deny-by-default.

Since Spring Security 5.5 and fully in 6, every authorization decision, whether for a URL or a method, is made by an object implementing one small interface: AuthorizationManager. The older AccessDecisionManager with its voters is gone. Knowing this one interface lets you write rules that no built-in expression can express: "only from the office network", "only during business hours", "only members of the tenant in the URL".

The real Spring types are read-only here. The runnable examples re-create the interface in plain Java, so you can write and compose managers and watch the decisions.

The interface

Java
@FunctionalInterface
public interface AuthorizationManager<T> {

    AuthorizationResult authorize(Supplier<Authentication> authentication, T object);
}

(In Spring Security 6 the return type is AuthorizationDecision, and 6.4 and later introduced the more general AuthorizationResult, which it extends. Your lambda can return either, depending on the version.)

Three ingredients:

  • Supplier<Authentication>: the current user, loaded lazily. If your rule does not need the user (for example it checks only the IP address), it never loads the session, which matters for cached or anonymous traffic.
  • T object: what is being protected. For URL rules it is a RequestAuthorizationContext (the request plus path variables); for methods it is a MethodInvocation.
  • The result: true (granted), false (denied) or, in the original design, null meaning "abstain".

Every authorizeHttpRequests rule is an AuthorizationManager<RequestAuthorizationContext>:

DSL Manager
hasRole("X"), hasAuthority("x") AuthorityAuthorizationManager
authenticated() AuthenticatedAuthorizationManager
permitAll() / denyAll() constant managers
access(manager) your manager

A custom rule for URLs

Java
http.authorizeHttpRequests(a -> a
    .requestMatchers("/internal/**").access(onOfficeNetwork())
    .requestMatchers("/tenants/{tenantId}/**").access(tenantMember())
    .anyRequest().authenticated());

static AuthorizationManager<RequestAuthorizationContext> onOfficeNetwork() {
    return (auth, ctx) -> {
        String ip = ctx.getRequest().getRemoteAddr();
        return new AuthorizationDecision(ip.startsWith("10.20."));
    };
}

static AuthorizationManager<RequestAuthorizationContext> tenantMember() {
    return (auth, ctx) -> {
        String tenant = ctx.getVariables().get("tenantId");
        boolean member = auth.get().getAuthorities().stream()
            .anyMatch(a -> a.getAuthority().equals("TENANT_" + tenant));
        return new AuthorizationDecision(member);
    };
}

ctx.getVariables() exposes the path variables of the matched pattern, so /tenants/{tenantId}/** can compare the id in the URL with what the user is entitled to. Beware that getRemoteAddr() is the address the server sees; behind a proxy or load balancer it is the proxy's address unless you configure forwarded headers (server.forward-headers-strategy) correctly. Never trust a raw X-Forwarded-For header from the client.

Composing managers

Small managers are only useful if they combine. AuthorizationManagers offers allOf, anyOf and not:

Java
var rule = AuthorizationManagers.allOf(
    AuthorityAuthorizationManager.<RequestAuthorizationContext>hasRole("ADMIN"),
    onOfficeNetwork());

(This is the version 6.3 and later API; older releases have AuthorizationManagers.allOf(new AuthorizationDecision(false), ...) with a default result argument. Check your release when copying.)

The model below implements the interface, the combinators and four sample rules. Run it and try changing the request values.

Java AuthorizationManager with allOf, anyOf and not (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at the userLoaded column. "Admin from home" fails at the network rule, before the user is loaded: allOf short-circuits and the lazy supplier is never called. For session-backed applications that means fewer session lookups for requests that were doomed anyway. Put the cheap, user-independent checks first.

Custom managers for methods

The same interface secures methods. To plug one in, define a bean advisor instead of annotating every method:

Java
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
static Advisor auditedOnlyDuringBusinessHours() {
    AuthorizationManager<MethodInvocation> manager = (auth, invocation) -> {
        LocalTime now = LocalTime.now(ZoneOffset.UTC);
        return new AuthorizationDecision(now.getHour() >= 9 && now.getHour() < 17);
    };
    var pointcut = AnnotationMatchingPointcut.forMethodAnnotation(BusinessHoursOnly.class);
    return new AuthorizationManagerBeforeMethodInterceptor(pointcut, manager);
}

This is how you build your own @BusinessHoursOnly annotation without SpEL. For most cases a bean referenced from @PreAuthorize("@policy.allowed(...)") (see the previous lesson) is simpler, and the interceptor route is for reusable, annotation-driven, cross-cutting rules.

Deny by default and observability

  • Finish every chain with anyRequest(). The DSL stores rules in order and the first match wins; an unmatched request falls through to the end. A chain ending in .anyRequest().denyAll() (or authenticated()) cannot accidentally leave a path open. In recent versions the lack of any rule behaves as "deny", but do not rely on silence.
  • Log denials, because a pattern of 403s from one user is a signal. Publish an AuthorizationDeniedEvent listener (@EventListener) and write who, what and where, never secrets:
Java
@Component
class DenialAudit {
    @EventListener
    void on(AuthorizationDeniedEvent<?> e) {
        log.warn("denied: user={} object={}", e.getAuthentication().get().getName(), e.getObject());
    }
}
  • Test decisions directly. A manager is a pure function of (user, object), which makes it very easy to unit test without starting Spring. See testing secured endpoints.
Java Unit-testing a manager as a pure function (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice the third test: a missing variable must lead to a denial, never to an exception or to true. Fail closed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does an AuthorizationManager receive?

    The user is supplied lazily, and the object is a request context for URLs or a method invocation for methods.
  2. 2. Why is Supplier<Authentication> lazy?

    Loading the authentication may touch the session; a rule that does not need it avoids that cost.
  3. 3. Which DSL call plugs your own manager into URL authorization?

    access(AuthorizationManager) accepts any manager for the matched requests.
  4. 4. Why order cheap, user-independent checks first inside allOf?

    Evaluation stops at the first denial, saving the more expensive checks.
  5. 5. What should a custom manager do when it cannot find the information it needs, such as a missing path variable?

    Authorization code must fail closed; unknown means no.

Summary

  • AuthorizationManager<T> is the single abstraction behind URL and method authorization.
  • Write custom rules for network, time, tenant or any data-dependent condition and plug them in with access(...) or a method interceptor.
  • Combine managers with allOf, anyOf and not; put cheap checks first.
  • Fail closed, end chains with a deny-by-default anyRequest() and audit denials with events.
  • Because a manager is a pure function, unit test it directly.

Next: JWT Structure: Header, Payload and Signature