0Pricing
Spring Security 6 & JWT Authentication · Lesson

Securing Endpoints with Custom Access Rules

Go beyond simple role checks by writing custom authorization logic in Spring Security 6 using AuthorizationManager, SpEL expressions, and request matchers.

Securing Endpoints with Custom Access Rules is a free Spring Security 6 & JWT Authentication lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Spring Security 6 & JWT Authentication learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Custom Access Rules?

Roles and methods cover most cases, but real apps need finer control: only the owner of a resource may edit it, or access depends on the time of day or a feature flag.

Spring Security 6 lets you express these rules declaratively or programmatically.

The authorizeHttpRequests DSL

In Spring Security 6 the modern way to secure URLs is authorizeHttpRequests. Each matcher maps a request pattern to an access rule.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers('/public/**').permitAll()
    .requestMatchers('/admin/**').hasRole('ADMIN')
    .anyRequest().authenticated());

Matching by HTTP Method

You can scope rules to a specific HTTP method, so reads and writes have different requirements.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers(HttpMethod.GET, '/api/orders/**').authenticated()
    .requestMatchers(HttpMethod.POST, '/api/orders/**').hasRole('MANAGER'));

SpEL with access()

The access() rule takes a Spring Expression Language (SpEL) condition for dynamic logic that plain matchers cannot express.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers('/reports/**')
    .access(new WebExpressionAuthorizationManager(
        "hasRole('ANALYST') and request.getHeader('X-Region') == 'EU'")));

The AuthorizationManager Interface

For full control, implement AuthorizationManager. It returns an AuthorizationDecision that grants or denies access based on the authentication and the request.

public interface AuthorizationManager<T> {
    AuthorizationDecision check(Supplier<Authentication> auth, T object);
}

Writing a Custom AuthorizationManager

Here is a manager that only allows access during business hours. The supplier gives the current user; the object holds request context.

AuthorizationManager<RequestAuthorizationContext> businessHours =
    (auth, ctx) -> {
        int hour = LocalTime.now().getHour();
        boolean ok = hour >= 9 && hour < 18;
        return new AuthorizationDecision(ok);
    };

Plugging It In

Attach your custom manager to a matcher with access(). Any request to the path is now evaluated by your logic.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers('/maintenance/**').access(businessHours)
    .anyRequest().authenticated());

Owner-Based Access

A common rule: only the resource owner can modify it. You can read a path variable from the request context to compare against the logged-in user.

AuthorizationManager<RequestAuthorizationContext> ownerOnly =
    (auth, ctx) -> {
        String pathUser = ctx.getVariables().get('userId');
        boolean same = auth.get().getName().equals(pathUser);
        return new AuthorizationDecision(same);
    };

Combining Rules

Spring evaluates matchers top to bottom and stops at the first match. Order matters: put specific rules before broad ones, and always end with a catch-all like anyRequest().

Denying by Default

A secure baseline denies everything not explicitly allowed. Use denyAll() as the final rule when you want a strict allow-list.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers('/health').permitAll()
    .anyRequest().denyAll());

Testing Access Rules

Verify your rules with @WithMockUser and MockMvc. Assert that authorized users get 200 and unauthorized users get 403.

mockMvc.perform(get('/admin/dashboard'))
    .andExpect(status().isForbidden());

Quick Check

Test your understanding of custom access rules.

Recap

You learned to write custom authorization in Spring Security 6:

  • Use the authorizeHttpRequests DSL with path and method matchers
  • Apply SpEL conditions via access()
  • Implement AuthorizationManager for dynamic, owner-based, or time-based rules
  • Order matters; end with a catch-all and prefer deny-by-default

These tools let you enforce business-specific security policies precisely.

Frequently asked questions

Is the “Securing Endpoints with Custom Access Rules” lesson free?

Yes — the full text of “Securing Endpoints with Custom Access Rules” is free to read here on the web, and the Spring Security 6 & JWT Authentication course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Spring Security 6 & JWT Authentication course, upgrade to CoddyKit PRO.

What will I learn in “Securing Endpoints with Custom Access Rules”?

Go beyond simple role checks by writing custom authorization logic in Spring Security 6 using AuthorizationManager, SpEL expressions, and request matchers. You practise Spring Security 6 & JWT Authentication with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Spring Security 6 & JWT Authentication?

No prior experience is required. Spring Security 6 & JWT Authentication on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Securing Endpoints with Custom Access Rules” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Spring Security 6 & JWT Authentication lesson?

Yes. Every Spring Security 6 & JWT Authentication lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Role-Based Access Control (RBAC)
  2. Method-Level Security with Annotations
  3. HttpSecurity Configuration Deep Dive
  4. Securing Endpoints with Custom Access Rules
← Back to Spring Security 6 & JWT Authentication