
# Request rules

`authorizeHttpRequests` lists the access rules of a chain: for each set of requests, what the caller needs. The first matching rule decides, and a request that no rule matches is denied. The rules use the router's path patterns, so a rule covers exactly what the controllers under it serve.

## Why

Rules on URLs protect a whole area of the application at once (`/api/admin/**`), including endpoints added later. Method security protects one service method wherever it is called from. Most applications use both: coarse rules on paths, finer rules on services.

## Example

```dart
@Bean()
SecurityFilterChain filterChain(HttpSecurity http) => http
    .authorizeHttpRequests((auth) => auth
        .requestMatchers('/', '/public/**', '/login').permitAll()
        .requestMatchers('/api/admin/**').hasRole('ADMIN')
        .requestMatchersFor(HttpMethod.get, ['/api/books/**']).permitAll()
        .requestMatchersFor(HttpMethod.delete, ['/api/books/**']).hasAnyRole(['ADMIN', 'EDITOR'])
        .requestMatchers('/api/orders/**').hasAuthority('SCOPE_orders')
        // Users may read and change only their own profile; admins any.
        .requestMatchers('/users/{id}/**').access(const SelfOrAdmin())
        .requestMatchers('/sign-up').anonymous()
        .anyRequest().authenticated())
    .formLogin()
    .build();

final class SelfOrAdmin implements AuthorizationManager<RequestAuthorizationContext> {
  const SelfOrAdmin();

  @override
  AuthorizationResult authorize(
    Authentication? Function() authentication,
    RequestAuthorizationContext context,
  ) {
    final user = authentication();
    final admin = user != null && user.authorities.any((a) => a.authority == 'ROLE_ADMIN');
    return AuthorizationDecision(
      admin ||
          (user != null &&
              user is! AnonymousAuthenticationToken &&
              user.name == context.variables['id']),
    );
  }
}
```

## Choosing requests

| Call | Requests |
|---|---|
| `requestMatchers(pattern, ...)` | Whose path matches one of up to six router patterns, any method. |
| `requestMatchersFor(method, [patterns])` | With that `HttpMethod` (any when `null`) and a matching path. Spring's `requestMatchers(HttpMethod, ...)`. |
| `requestMatchersOf([matchers])` | Matched by any of the `RequestMatcher`s. |
| `anyRequest()` | Every request no earlier rule matched; it must be the last rule. |

Patterns are the router's: `/api/**`, `/users/{id}`, `/files/*.pdf`. They are matched on the path the router sees, after the context path. Paths are case-sensitive and a trailing slash counts: protect `/admin` and `/admin/**` when both exist.

### Request matchers

| Matcher | Matches |
|---|---|
| `PathPatternRequestMatcher(pattern, method:)` | A path pattern, maybe with a method. |
| `HttpMethodRequestMatcher(method)` | A method. |
| `RequestHeaderRequestMatcher(name, [value])` | A header present, or with that value. |
| `MediaTypeRequestMatcher(...)` | The media types of `Accept`. |
| `AndRequestMatcher([...])`, `OrRequestMatcher([...])`, `NegatedRequestMatcher(m)` | Combinations. |
| `AnyRequestMatcher.instance` | Every request. |

Implement `RequestMatcher` (or extend `SimpleRequestMatcher` and write `matches(request)`) for a test of your own.

## What the requests need

| Call | Lets through |
|---|---|
| `permitAll()` | Everyone, logged in or not: public pages, the login page, static assets. |
| `denyAll()` | Nobody. |
| `authenticated()` | Users who logged in; anonymous ones are asked to log in. |
| `fullyAuthenticated()` | The same as `authenticated()` here (there is no remember-me). |
| `anonymous()` | Only users who have not logged in (a sign-up page); logged-in users get `403`. |
| `hasRole('ADMIN')` | The authority `ROLE_ADMIN`. Writing `ROLE_ADMIN` is an `ArgumentError`. |
| `hasAnyRole([...])` | One of the roles, each without the prefix. |
| `hasAuthority('SCOPE_read')` | The authority, written in full. |
| `hasAnyAuthority([...])` | One of the authorities. |
| `access(manager)` | What the `AuthorizationManager<RequestAuthorizationContext>` decides; it gets the request and the path variables of the rule's pattern (`context.variables['id']`). An abstention (`null`) denies. |

Role and authority checks use the `RoleHierarchy` bean, and `hasRole` the prefix of the `GrantedAuthorityDefaults` bean (`ROLE_` without one). `AuthorizationManagers.anyOf` and `allOf` combine managers.

## What a refused request gets

| Caller | Answer |
|---|---|
| Not logged in, a browser asking for a page | A redirect to the login page; the page is saved for after the login. |
| Not logged in, a program (`curl`, JSON) | `401` with `WWW-Authenticate: Basic` (or `Bearer` for a resource server). |
| Not logged in, a script (`X-Requested-With: XMLHttpRequest`) | A plain `401`, so no browser password dialog appears. |
| Logged in, not allowed | `403` as a `ProblemDetail`. |

`exceptionHandling((e) => e.authenticationEntryPoint(...).accessDeniedHandler(...))` changes these answers.

## Rules of thumb

- **Deny by default.** End with `anyRequest().authenticated()` or `denyAll()`. A request no rule matches is denied anyway, but say it.
- **Specific first.** The first match wins: `/api/admin/**` before `/api/**`.
- **Let everyone reach the login page** and the error and static resources it needs.
- **Do not rely on the rules alone** for data that depends on the user ("my orders"): check it in the service with method security or in the query.

## In Spring (Java)

```java
http.authorizeHttpRequests(auth -> auth
    .requestMatchers("/public/**").permitAll()
    .requestMatchers(HttpMethod.GET, "/api/books/**").permitAll()
    .requestMatchers("/users/{id}/**").access(new SelfOrAdmin())
    .anyRequest().authenticated());
```

The same calls, except `requestMatchersFor` for a method (no overloading) and `requestMatchersOf` for matchers. Not here: `hasIpAddress`, regex matchers, SpEL in request rules (`access` takes a manager), and `hasAllAuthorities` (use `AuthorizationManagers.allOf`).

## See also

- [The filter chain](filter-chain.md)
- [Method security](../spring-security-core/method-security.md)
- [@RequestMapping](../spring-boot-starter-web/controllers/request-mapping.md)
