Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 39 ยท Filter Chain and Configuration

Request Matchers and Authorization Rules

Master authorizeHttpRequests, requestMatchers, path patterns, HTTP methods and first-match-wins rule ordering, and avoid the rule mistakes that leave URLs open.

The most common piece of security configuration is a list of rules: "this URL is public, that one needs ADMIN, everything else needs a login". The list is written inside authorizeHttpRequests, and every rule has two parts: a matcher that decides which requests it applies to, and an access decision such as permitAll() or hasRole("ADMIN").

This lesson explains how matchers work, which path patterns exist, the single most important rule about ordering, and the pitfalls (trailing slashes, /**, mixed servlets) that cause real vulnerabilities. A runnable stand-in implements Ant-style matching and first-match evaluation so you can test your own rule lists.

Anatomy of a rule list

Java
http.authorizeHttpRequests(auth -> auth
    .requestMatchers("/", "/login", "/css/**", "/js/**").permitAll()
    .requestMatchers(HttpMethod.GET, "/api/products/**").permitAll()
    .requestMatchers("/api/products/**").hasAnyRole("EDITOR", "ADMIN")
    .requestMatchers("/admin/**").hasRole("ADMIN")
    .requestMatchers("/reports/{year}").access(yearRule())
    .anyRequest().authenticated());

When a request arrives, AuthorizationFilter walks the rules from the top and uses the first rule whose matcher matches. It does not keep looking for a "better" match. That one sentence explains most rule bugs.

The access decisions you will use most:

Method Meaning
permitAll() Everyone, including anonymous callers
denyAll() Nobody (useful to block a path)
authenticated() Any logged-in user (not anonymous)
fullyAuthenticated() Logged in and not via remember-me
hasRole("ADMIN") / hasAnyRole(...) Has ROLE_ADMIN (prefix added automatically)
hasAuthority("report:read") / hasAnyAuthority(...) Has exactly that authority string
access(...) Custom AuthorizationManager, see authorization managers

Path patterns

requestMatchers("/admin/**") uses path patterns (the same PathPattern syntax as Spring MVC):

Pattern Matches
/about Exactly /about
/files/* /files/a.txt, not /files/a/b.txt
/files/** /files, /files/a.txt, /files/a/b/c.txt
/users/{id} /users/42 (one segment, captured as id)
/users/{id:[0-9]+} Only numeric ids
/img/?.png /img/a.png (one character)

Since Spring Security 6 the requestMatchers(String...) method picks the right matcher for your setup: it uses the Spring MVC matching when Spring MVC is present, so a rule for /admin also covers /admin/ and /admin.json only if MVC would map them to the same handler. This closes an old class of bypasses where the security rule and the controller mapping disagreed about what a URL means. If you have several servlets (for example the H2 console next to Spring MVC) the method refuses to guess and you must say which with PathPatternRequestMatcher.withDefaults().matcher("/h2-console/**") or the servletPath variant.

You can also match on the HTTP method, on a regular expression (RegexRequestMatcher), or with your own RequestMatcher lambda: request -> request.getHeader("X-Internal") != null.

The ordering rule

Because the first match wins, write rules from the most specific to the most general, and finish with anyRequest():

Java
// BROKEN: the /admin rule can never be reached
.requestMatchers("/**").authenticated()
.requestMatchers("/admin/**").hasRole("ADMIN")

Here every authenticated user can reach /admin/**, because /** matched first. Spring helps a little: it rejects a configuration where a rule appears after anyRequest(), because the rule would be unreachable. It cannot catch the earlier example, since /** and anyRequest() are not the same matcher. Treat rule lists like if / else if chains.

flowchart TB
  A["Request: GET /admin/users"] --> B{"Rule 1<br/>/, /login, /css/**"}
  B -- "no match" --> C{"Rule 2<br/>GET /api/products/**"}
  C -- "no match" --> D{"Rule 3<br/>/admin/**"}
  D -- "match" --> E["hasRole ADMIN decides<br/>(later rules are never read)"]

Evaluation stops at the first matching rule.

A rule evaluator you can run

The stand-in below implements Ant-style patterns (?, *, **, ) and the first-match rule walk. It then runs a broken and a correct rule list against the same requests.

Java First match wins: pattern matcher and rule list

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.

In the broken list the plain user gets ALLOW for /admin/users. In the good list the same request is 403, and the anonymous caller gets 401. Also note POST /api/products/7: the GET-only public rule does not match, so it falls through to /** and requires login.

Shadowed rules are easy to miss in a long list, so here is a tiny linter. It reports every rule that can never be reached because an earlier rule already covers everything it would match (simplified to prefix patterns ending in /**).

Java Find unreachable rules

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.

"Deny by default" and anyRequest

End every list with anyRequest().authenticated() (or denyAll() for a strict allow-list design). If you omit anyRequest, requests matching no rule are allowed in some configurations; the explicit final rule means you never wonder. The stricter style is:

Java
.requestMatchers("/public/**").permitAll()
.requestMatchers("/api/**").hasRole("API")
.anyRequest().denyAll()

which means a new URL you forget to list is blocked, not accidentally exposed.

Rules versus static resources

Do not use web.ignoring() for static files any more. An ignored request skips all filters, so it loses security headers and cannot be audited. Use permitAll() instead. For the common Boot locations (/css/**, /js/**, /images/**, /webjars/**, /favicon.ico), the helper PathRequest.toStaticResources().atCommonLocations() builds a matcher.

Mistakes to avoid

  • Trailing-slash and extension surprises. With the MVC-aware matcher this is mostly solved, but custom regex matchers can still miss /admin/ or /admin.json.
  • Method-less rules for write operations. permitAll() on /api/comments/** opens DELETE too. Add HttpMethod.GET when you mean reads.
  • URL rules as the only protection. URL rules guard paths; if the same service method is reachable through two URLs, or from a scheduled job, only method security guards the method itself. Use both for important operations.
  • Using hasRole("ROLE_ADMIN"). hasRole adds the prefix and Spring complains when you add it twice.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Rules in order: requestMatchers("/").authenticated() then requestMatchers("/admin/").hasRole("ADMIN"). A logged-in USER requests /admin/x. What happens?

    The first matching rule wins. Put specific rules before general ones.
  2. 2. Which pattern matches /files/a/b/c.txt?

    ** spans several path segments; * and {name} match a single segment.
  3. 3. Why is permitAll() on /api/comments/** without an HTTP method risky?

    A rule without a method matches every method. Restrict it to GET if only reads are public.
  4. 4. What is the best replacement for web.ignoring() on static resources?

    Ignored requests skip all security filters. permitAll keeps them in the chain, with security headers.

Summary

  • authorizeHttpRequests holds an ordered list of matcher plus access rules; the first matching rule wins.
  • Order rules from specific to general and end with anyRequest(); prefer denyAll() for strict allow-lists.
  • Path patterns: ?, *, ** and ; requestMatchers(String...) follows Spring MVC mapping.
  • Restrict public rules to the safe HTTP method and avoid web.ignoring().
  • URL rules complement, and do not replace, method-level checks.

Next: Multiple filter chains