Cheatsheet

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).

Diagram (UML)

ApplicationContextAthleteSecurityFilterChainAuthorizationFilterWodControllerResultService (proxy)CsrfFilterExceptionTranslationFilterSecurityContextResultService

Key pieces

  • authorizeHttpRequests(auth -> auth.requestMatchers(...).hasRole(...)…anyRequest()…)
  • permitAll(), denyAll(), authenticated(), hasRole(), hasAnyRole(), hasAuthority(), hasAnyAuthority(), access(...)
  • @EnableMethodSecurity (prePostEnabled by default; securedEnabled, jsr250Enabled)
  • @PreAuthorize("SpEL"), @PostAuthorize("… returnObject …"), @Secured("ROLE_X"), @RolesAllowed("X")
  • AuthorizationFilter, ExceptionTranslationFilter, AccessDeniedException
  • CSRF: CsrfFilter, csrf(...); in tests, .with(csrf())

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();
}

Remember for the exam

  • URL rules are evaluated top-down and the first match wins: specific before general
  • anyRequest() goes last; no rule can be added after it
  • hasRole("ADMIN") checks the authority ROLE_ADMIN; hasAuthority("ROLE_ADMIN") is the same, written in full
  • @PreAuthorize supports SpEL with the arguments (#athlete) and authentication; @PostAuthorize, also returnObject
  • @Secured uses the full authority name (ROLE_COACH) and no SpEL; @RolesAllowed (JSR-250) uses the role name
  • Not authenticated → 401; authenticated without permission → 403
  • CSRF is on by default: state-changing methods (POST, PUT, DELETE, PATCH) need a token; GET doesn't

Exam traps

  • hasRole("ROLE_ADMIN") fails: Spring adds the prefix and would look for ROLE_ROLE_ADMIN (in fact it throws when configured)
  • Putting requestMatchers("/api/**").authenticated() before a more specific rule overrides it
  • Method security works with proxies: internal calls (this) and private methods aren't checked
  • @PostAuthorize runs the method before checking: it can't prevent side effects
  • Disabling CSRF only makes sense for stateless APIs (no session or authentication cookies)

← Authorization: URLs and methods · Run it