liveBook · Manning

@PreAuthorize

As explained in Spring Security in Action, Second Edition

@PreAuthorize is a Spring Security annotation that authorizes a method invocation by evaluating a Spring Expression Language expression before the method runs.

@PreAuthorize protects a method by evaluating a Spring Expression Language (SpEL) authorization rule before the method executes. Enable method security with @EnableMethodSecurity; otherwise, method-level authorization is disabled. section 11.2 section 11.5

Apply it to method-level authorization by:

  • Checking authorities with expressions such as hasAuthority(), hasAnyAuthority(), hasRole(), or hasAnyRole(). section 11.2
  • Referencing method parameters and authentication data to enforce resource ownership. section 11.2
  • Separating complex authorization logic into a PermissionEvaluator when annotations become difficult to read. section 11.5

Authority-based protection

@PreAuthorize("hasAuthority('write')") allows Emma, who has write authority, to call getName(), while Natalie receives a 403 Forbidden response. section 11.2

Listing 11.6 The NameService class defining the protected method
@Service
public class NameService {

  private Map<String, List<String>> secretNames = 
    Map.of(
     "natalie", List.of("Energico", "Perfecto"),
     "emma", List.of("Fantastico"));

  @PreAuthorize                                     #1
    ("#name == authentication.principal.username")
  public List<String> getSecretNames(String name) {
    return secretNames.get(name);
  }
}

Inspect a parameter-based rule that compares the requested name with authentication.principal.username. section 11.2

How Spring Security in Action, Second Edition covers it

How deep it goes
Demonstrates enabling method security, annotating methods, evaluating authorities and parameters, and testing allowed and denied calls.
Examples
Uses write-authorized users, a protected greeting service, secret-name ownership, Java listings, and cURL responses.
What it assumes
Assumes basic Spring configuration, authenticated users, authorities, UserDetailsService, and PasswordEncoder.
What you can do after
Operate method security by enabling it, writing SpEL rules, and testing permitted and forbidden invocations.
How it connects
Connects Spring Security, SpEL, method security, authentication, authorization, PermissionEvaluator, and @PostAuthorize.

Also explained in

Compare how 2 books explain @PreAuthorize →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Security in Action, Second Edition. The section links point to the parts of the book it draws on.