Definition
- permitAll() – grants access to the matched URL without requiring authentication; anonymous users, authenticated users, and bots can all reach the endpoint.
- authenticated() – requires a valid Authentication in the SecurityContext; returns 401 if the user is not authenticated.
- denyAll() – denies access to every request, regardless of authentication or authority; returns 403 for authenticated users and 401 for anonymous users.
- hasRole() / hasAuthority() – more granular alternatives that require specific roles or permissions beyond just being authenticated.
- anyRequest() – the catch-all matcher that applies to any URL not already matched by a previous requestMatchers rule.
In a bank branch, permitAll() is the public lobby: anyone can walk in. authenticated() is the customer service area: you need a valid token/ID to enter. denyAll() is a sealed vault room that nobody is allowed to enter right now, not even the branch manager. And anyRequest().authenticated() is the rule that says "if you are not in the lobby, you need to show your ID."
Understanding the Concepts
How do permitAll, authenticated, and denyAll work?
These three methods define the most basic authorization decisions in Spring Security:
package com.bank.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.Customizer;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class BankSecurityConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
// Public: no authentication needed
.requestMatchers("/api/public/**").permitAll()
.requestMatchers("/actuator/health").permitAll()
.requestMatchers("/api/interest-rates").permitAll()
// Restricted: requires authentication
.requestMatchers("/api/accounts/**").authenticated()
.requestMatchers("/api/transfers/**").authenticated()
// Locked: nobody can access
.requestMatchers("/api/internal/**").denyAll()
.requestMatchers("/api/debug/**").denyAll()
// Role-based: requires specific authority
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.requestMatchers("/api/loans/approve").hasAuthority("LOAN_APPROVE")
// Catch-all: everything else requires authentication
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults())
.build();
}
}
What is the comparison between all authorization methods?
| Method | Who can access | HTTP response if denied | Use case |
|---|---|---|---|
permitAll() | Everyone (anonymous + authenticated) | N/A (always allowed) | Health checks, public API, login page |
authenticated() | Any authenticated user | 401 Unauthorized | General protected endpoints |
denyAll() | Nobody | 403 Forbidden (authenticated) / 401 (anonymous) | Disabled endpoints, internal-only |
hasRole("ADMIN") | Users with ROLE_ADMIN | 403 Forbidden | Admin operations |
hasAuthority("X") | Users with exact authority X | 403 Forbidden | Fine-grained permissions |
hasAnyRole("A","B") | Users with ROLE_A or ROLE_B | 403 Forbidden | Multiple roles |
Why does the order of requestMatchers matter?
Spring Security evaluates matchers in declaration order. The first match wins. If a broad rule comes before a specific rule, the specific rule is never reached.
// WRONG: The broad rule matches first, specific rule is unreachable
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated() // Matches everything
.requestMatchers("/api/public/**").permitAll() // Never reached
)
// CORRECT: Specific rules first, catch-all last
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**").permitAll() // Specific: matched first
.anyRequest().authenticated() // Catch-all: everything else
)
Does permitAll bypass all security filters?
No. permitAll() only skips the authorization check. Other security filters still run:
- CSRF filter still validates CSRF tokens for state-changing requests (POST, PUT, DELETE).
- CORS filter still applies CORS headers.
- Security context is still populated if the request includes valid credentials.
- Rate limiting (if configured) still applies.
This means a permitAll() POST endpoint still requires a valid CSRF token in session-based security configurations.
// This endpoint is permitAll, but POST requests still need CSRF token
// unless CSRF is explicitly disabled
.requestMatchers("/api/public/feedback").permitAll()
To truly bypass all security processing, you can use web.ignoring(), but this is rarely recommended because it skips all security filters including security headers:
// Not recommended: bypasses ALL security filters
@Bean
WebSecurityCustomizer webSecurityCustomizer() {
return web -> web.ignoring()
.requestMatchers("/static/**", "/favicon.ico");
}
When should you use denyAll?
Common use cases:
1. Disable debug endpoints in production:
.requestMatchers("/api/debug/**").denyAll()
2. Block internal-only endpoints exposed by libraries:
.requestMatchers("/actuator/env", "/actuator/configprops").denyAll()
3. Temporarily disable a feature under maintenance:
.requestMatchers("/api/international-transfers/**").denyAll()
4. Catch-all for safety (deny anything not explicitly permitted):
.anyRequest().denyAll() // Nothing gets through unless explicitly allowed
What is the difference between anyRequest().authenticated() and anyRequest().denyAll() as a catch-all?
| Catch-all | Behavior | Use case |
|---|---|---|
.anyRequest().authenticated() | New endpoints are accessible to any authenticated user by default | Most applications: new endpoints get baseline protection |
.anyRequest().denyAll() | New endpoints are blocked until explicitly permitted | High-security banking applications: nothing is accessible by accident |
For banking applications handling sensitive financial data, .anyRequest().denyAll() is safer. It forces every new endpoint to be explicitly added to the authorization rules. If a developer forgets to add a rule for a new endpoint, it is blocked rather than open to all authenticated users.
What are common mistakes?
1. No catch-all rule:
// WRONG: Endpoints not listed have no authorization rule
// Spring Security 6 throws an error for unmatched requests
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
// Missing: .anyRequest().authenticated()
)
2. Using permitAll for endpoints that should be authenticated:
// WRONG: Account balance should not be public
.requestMatchers("/api/accounts/*/balance").permitAll()
// CORRECT: Require authentication
.requestMatchers("/api/accounts/*/balance").authenticated()
3. Confusing authenticated() with fullyAuthenticated():
// authenticated(): accepts remember-me authentication
.requestMatchers("/api/profile").authenticated()
// fullyAuthenticated(): rejects remember-me, requires full login
.requestMatchers("/api/transfers").fullyAuthenticated()
For banking applications, use fullyAuthenticated() for sensitive operations like fund transfers, and authenticated() for read-only operations.
What should a senior engineer know?
- In Spring Security 6, every request must match a rule. If a request does not match any
requestMatchers, Spring Security throws an error. This is a safety feature to prevent accidental exposure. permitAll()returnsAuthorizationDecision(true)from theAuthorizationManager. The request still passes through security filters.- For OAuth2 resource servers,
authenticated()means a valid bearer token must be present.permitAll()means the endpoint can be accessed without a token. - In tests, use
@WithAnonymousUserto test permitAll endpoints and@WithMockUserto test authenticated endpoints.
Visual Overview
┌──────────────────────────────────────────────────┐
│ Authorization Rule Evaluation │
└──────────────────────┬───────────────────────────┘
│
Request: GET /api/accounts/SAV2001
│
┌────────────────────┼────────────────────────┐
│ Rule 1: /api/public/** → permitAll() │
│ Match? NO │
├─────────────────────────────────────────────┤
│ Rule 2: /api/accounts/** → authenticated() │
│ Match? YES │
│ User authenticated? Check... │
│ YES → Allow (200) │
│ NO → Deny (401) │
├─────────────────────────────────────────────┤
│ Rule 3: /api/internal/** → denyAll() │
│ (not reached) │
├─────────────────────────────────────────────┤
│ Rule 4: anyRequest() → authenticated() │
│ (not reached) │
└─────────────────────────────────────────────┘
Key Takeaway
The three fundamental authorization decisions in Spring Security are permitAll, authenticated, and denyAll. Every endpoint in your application falls into one of these categories, or a more specific variant like hasRole or hasAuthority.
permitAll makes an endpoint public. It does not require any authentication, but it still passes through other security filters like CSRF and CORS. authenticated requires a valid identity in the SecurityContext. denyAll blocks everyone, regardless of their role or credentials.
In a banking application, Rajesh uses permitAll for the interest rate lookup API that anyone can access. He uses authenticated for account balance queries that require a login. He uses denyAll for internal debug endpoints that should never be exposed. And he ends every rule set with anyRequest().denyAll() as a safety net: if a developer adds a new endpoint without adding a security rule, it is blocked by default rather than accidentally exposed.
The ordering of rules is critical. Spring Security evaluates requestMatchers in declaration order and uses the first match. A broad rule before a specific rule makes the specific rule unreachable. Always put specific matchers first and the catch-all last.
The one sentence to remember: permitAll lets anyone in, authenticated requires a valid identity, denyAll blocks everyone, and the order of requestMatchers determines which rule fires first.
---