Authorization: URLs and methods

Key idea
Once the user is authenticated, Spring Security decides whether they may access each resource. At URL level, with rules in `authorizeHttpRequests` evaluated in order; at method level, with `@PreAuthorize`, `@PostAuthorize`, `@Secured` or `@RolesAllowed`, applied by a proxy. If access is denied, the response is 401 (not authenticated) or 403 (not allowed).
In the box
The box's permissions were ifs scattered across the controllers, and one was wrong. Declare which role may do what in the filter chain, understand hasRole versus hasAuthority, protect methods with @PreAuthorize and @PostAuthorize, and find out why a POST without a CSRF token gives 403.
AthleteIfBasedWodController

The athlete, with role COACH, sends DELETE wod to IfBasedWodController, highlighted in red, which lets it through because of a badly copied if.

The AuthorizationFilter, highlighted, receives POST /api/wods and asks the SecurityContext whether the user has ROLE_COACH.

The SecurityContext, highlighted, receives the hasRole("ADMIN") check, which amounts to looking for the authority ROLE_ADMIN.

The AuthorizationFilter sends AccessDenied to the ExceptionTranslationFilter, highlighted, which answers 403 (or 401 if the user is anonymous).

The controller calls history("leo") on the ResultService proxy, highlighted, which checks in the SecurityContext whether the argument matches the user's name.

The ResultService proxy passes result(2) to the real service and checks the returned object before handing it over; both are highlighted.

The controller calls the ResultService proxy, highlighted, as ana: only the calls about her own data get through.

A POST without a token reaches the CsrfFilter, highlighted, which rejects it with 403 before looking at roles.

Final view: the filter chain, the AuthorizationFilter, the controller and the ResultService proxy on top; the CsrfFilter, the ExceptionTranslationFilter, the SecurityContext and the real service below.

Step 1 of 9

Permissions made of ifs

IfBasedWodController checks permissions inside each method with request.isUserInRole(...):

  • publish requires COACH. Fine.
  • delete also requires COACH… but deleting WODs should be ADMIN only. Someone copied the if and didn't change it.

Step 2 of 9

URL rules: the first match wins

In the SecurityFilterChain, authorizeHttpRequests declares the rules, and the AuthorizationFilter applies them to each request:

  • /api/public/** → permitAll().
  • DELETE /api/wods/** → hasRole("ADMIN").
  • POST /api/wods/** → hasRole("COACH").
  • /api/admin/** → hasAuthority("ROLE_ADMIN").
  • Everything else → authenticated().

They're evaluated top-down and the first match wins. That's why specific goes first and anyRequest() last (Spring won't let you add rules after it).

Step 3 of 9

Roles and authorities

For Spring Security everything is an authority (GrantedAuthority): strings like ROLE_ADMIN or wods:write. A role is an authority with the ROLE_ prefix:

  • hasRole("ADMIN") checks ROLE_ADMIN (Spring adds the prefix).
  • hasAuthority("ROLE_ADMIN") checks exactly that string.
  • hasAnyRole("COACH", "ADMIN"), hasAnyAuthority(...), denyAll() and access(...) for custom rules.

Step 4 of 9

401 or 403

When the AuthorizationFilter denies access, it throws AccessDeniedException. The ExceptionTranslationFilter turns it into a response:

  • If the user is anonymous, it starts authentication (AuthenticationEntryPoint): 401, with HTTP Basic.
  • If they're authenticated but not allowed, AccessDeniedHandler: 403.

The test walks through it: anonymous on /api/wods → 401; ana (ATHLETE) publishing → 403; marta (COACH) publishing → 200, but deleting → 403; root (ADMIN) deleting → 200.

Step 5 of 9

Method security: @PreAuthorize

URL rules know nothing about data. "An athlete may see their own history, a coach everyone's" needs to look at the arguments. That's what method security is for:

  • @EnableMethodSecurity enables it (with @PreAuthorize/@PostAuthorize by default).
  • @PreAuthorize("hasRole('COACH') or #athlete == authentication.name") evaluates SpEL before running history(athlete): #athlete is the argument and authentication, the current user.

It works through a proxy around ResultService (the same AOP mechanism). If the expression is false: AccessDeniedException → 403.

Step 6 of 9

@PostAuthorize, @Secured and @RolesAllowed

More method annotations:

  • @PostAuthorize("returnObject.athlete() == authentication.name or hasRole('COACH')"): checks after running, looking at the result. Useful for "you may only see your own results". Careful: the method has already run.
  • @Secured("ROLE_COACH"): Spring's older annotation. Full authority name and no SpEL. Needs securedEnabled = true.
  • @RolesAllowed("ADMIN"): the JSR-250 standard. Role name (the prefix is added). Needs jsr250Enabled = true.

Step 7 of 9

Every athlete, their own

MethodSecurityTest calls the service directly, no web, with @WithMockUser(username = "ana", roles = "ATHLETE"):

  • history("ana") works; history("leo") throws AccessDeniedException.
  • result(1) (Ana's) works; result(2) (Leo's) throws the exception after running.
  • countAll() (@Secured("ROLE_COACH")) throws too.

With no user in the context at all, method security doesn't even run the method: AuthenticationCredentialsNotFoundException.

Step 8 of 9

CSRF: the surprising 403

With CSRF on (the default), a state-changing request (POST, PUT, DELETE, PATCH) needs a valid CSRF token. Without one, the CsrfFilter answers 403, even if the user has the right role.

  • It protects against another site making a logged-in user's browser send requests with their cookies.
  • In tests: .with(csrf()) adds a valid token.
  • GET, HEAD, OPTIONS and TRACE aren't checked (they shouldn't change anything).

Step 9 of 9

Recap

  • URL: authorizeHttpRequests, in order, first match wins; anyRequest() last.
  • Roles = authorities with ROLE_: hasRole("X") = hasAuthority("ROLE_X").
  • 401 anonymous, 403 not allowed (ExceptionTranslationFilter).
  • Methods: @EnableMethodSecurity + @PreAuthorize (SpEL, arguments), @PostAuthorize (returnObject), @Secured, @RolesAllowed; via a proxy.
  • CSRF on by default: POST without a token → 403.

Cheatsheet →

Code

IfBasedWodController.java

/** Before: permission checks scattered as ifs inside each handler. */
public class IfBasedWodController {
    public ResponseEntity<String> publish(HttpServletRequest request, String wod) {
        if (!request.isUserInRole("COACH")) {                 // copied into every write method…
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        return ResponseEntity.ok("published " + wod);
    }

    public ResponseEntity<String> delete(HttpServletRequest request, String wod) {
        if (!request.isUserInRole("COACH")) {                 // …forgotten here: should be ADMIN!
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        return ResponseEntity.ok("deleted " + wod);
    }
}

SecurityConfig.java

@Bean
public SecurityFilterChain api(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth                       // evaluated top-down: first match wins
            .requestMatchers("/api/public/**").permitAll()
            .requestMatchers(HttpMethod.DELETE, "/api/wods/**").hasRole("ADMIN")   // specific first…
            .requestMatchers(HttpMethod.POST, "/api/wods/**").hasRole("COACH")
            .requestMatchers("/api/admin/**").hasAuthority("ROLE_ADMIN")          // same as hasRole("ADMIN")
            .anyRequest().authenticated())                                         // …general last
        .httpBasic(withDefaults());                               // CSRF stays ON (the default)
    return http.build();
}

SecurityConfig.java

@Bean
public SecurityFilterChain api(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth                       // evaluated top-down: first match wins
            .requestMatchers("/api/public/**").permitAll()
            .requestMatchers(HttpMethod.DELETE, "/api/wods/**").hasRole("ADMIN")   // specific first…
            .requestMatchers(HttpMethod.POST, "/api/wods/**").hasRole("COACH")
            .requestMatchers("/api/admin/**").hasAuthority("ROLE_ADMIN")          // same as hasRole("ADMIN")
            .anyRequest().authenticated())                                         // …general last
        .httpBasic(withDefaults());                               // CSRF stays ON (the default)
    return http.build();
}

UrlAuthorizationTest.java

@Test
void rolesPerUrlAndMethod() throws Exception {
    mvc.perform(get("/api/public/wods/today")).andExpect(status().isOk());              // permitAll
    mvc.perform(get("/api/wods")).andExpect(status().isUnauthorized());                 // 401: anonymous
    mvc.perform(get("/api/wods").with(httpBasic("ana", "fran321"))).andExpect(status().isOk());
    mvc.perform(post("/api/wods").param("name", "Cindy").with(httpBasic("ana", "fran321")).with(csrf()))
        .andExpect(status().isForbidden());                                             // 403: not a COACH
    mvc.perform(post("/api/wods").param("name", "Cindy").with(httpBasic("marta", "wod123")).with(csrf()))
        .andExpect(status().isOk());
    mvc.perform(delete("/api/wods/Cindy").with(httpBasic("marta", "wod123")).with(csrf()))
        .andExpect(status().isForbidden());                                             // DELETE needs ADMIN
    mvc.perform(delete("/api/wods/Cindy").with(httpBasic("root", "admin1")).with(csrf()))
        .andExpect(status().isOk());
}

ResultService.java

@PreAuthorize("hasRole('COACH') or #athlete == authentication.name") // SpEL with the argument
public String history(String athlete) {
    return athlete + ": Fran 3:51, Murph 45:10";
}

ResultService.java

@PostAuthorize("returnObject.athlete() == authentication.name or hasRole('COACH')") // checks the RESULT
public Result result(long id) {
    return results.get(id);
}

@Secured("ROLE_COACH")          // older Spring annotation: full authority name, no SpEL
public int countAll() {
    return results.size();
}

@RolesAllowed("ADMIN")          // JSR-250: role name, ROLE_ prefix added for you
public String purge() {
    return "purged";
}

MethodSecurityTest.java

@Test
@WithMockUser(username = "ana", roles = "ATHLETE")
void anAthleteSeesOnlyHerOwnData() {
    assertThat(results.history("ana")).startsWith("ana:");          // #athlete == authentication.name
    assertThatThrownBy(() -> results.history("leo"))
        .isInstanceOf(AccessDeniedException.class);                 // → 403 through the web layer
    assertThat(results.result(1).athlete()).isEqualTo("ana");       // @PostAuthorize on the return value
    assertThatThrownBy(() -> results.result(2)).isInstanceOf(AccessDeniedException.class);
    assertThatThrownBy(() -> results.countAll()).isInstanceOf(AccessDeniedException.class); // @Secured
}

UrlAuthorizationTest.java

@Test
@WithMockUser(roles = "COACH")
void csrfProtectsStateChangingRequests() throws Exception {
    mvc.perform(post("/api/wods").param("name", "Cindy"))
        .andExpect(status().isForbidden());                     // no CSRF token: rejected
    mvc.perform(post("/api/wods").param("name", "Cindy").with(csrf()))
        .andExpect(status().isOk());                            // valid token
    mvc.perform(get("/api/wods")).andExpect(status().isOk());   // GET is never checked
}

SecurityConfig.java

@Bean
public SecurityFilterChain api(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth                       // evaluated top-down: first match wins
            .requestMatchers("/api/public/**").permitAll()
            .requestMatchers(HttpMethod.DELETE, "/api/wods/**").hasRole("ADMIN")   // specific first…
            .requestMatchers(HttpMethod.POST, "/api/wods/**").hasRole("COACH")
            .requestMatchers("/api/admin/**").hasAuthority("ROLE_ADMIN")          // same as hasRole("ADMIN")
            .anyRequest().authenticated())                                         // …general last
        .httpBasic(withDefaults());                               // CSRF stays ON (the default)
    return http.build();
}

Quiz

1. You have .requestMatchers("/api/**").authenticated() and below it .requestMatchers("/api/admin/**").hasRole("ADMIN"). An authenticated ATHLETE requests /api/admin/stats. What happens?

2. Which authority does hasRole("COACH") check?

3. What does @PreAuthorize("hasRole('COACH') or #athlete == authentication.name") allow on history(String athlete)?

4. What's needed for @PreAuthorize to take effect in a Spring Boot application?

5. An authenticated user with role COACH does a POST with MockMvc without .with(csrf()), and CSRF protection is on. What's the response?

6. What sets @PostAuthorize apart from @PreAuthorize?

Cheatsheet → · Mock exam →

Run it