liveBook · Manning

@EnableMethodSecurity

As explained in Spring Security in Action, Second Edition

@EnableMethodSecurity is a Spring Security annotation that enables method-level authorization support and selected method-security annotations.

@EnableMethodSecurity activates method-level authorization in a Spring configuration class. Method security is disabled by default, so annotated service methods have no method authorization until this annotation is added. section 11.1.2 section 11.5

After enabling it, the application can use several method-authorization approaches:

  • Use @PreAuthorize to check a SpEL authorization expression before a method executes. section 11.5
  • Use @PostAuthorize to check the caller after execution, including rules based on the returned value. section 11.5
  • Enable @RolesAllowed with jsr250Enabled = true or @Secured with securedEnabled = true; both are less powerful than pre- and postauthorization. section 11.4
  • Apply method security alongside authentication approaches such as HTTP Basic or OAuth 2. section 11.1.2

Enable authorization for a document service

Place @EnableMethodSecurity on the configuration class, then protect a service method with @PostAuthorize("hasPermission(returnObject, 'ROLE_admin')") or @PreAuthorize("hasPermission(#code, 'document', 'ROLE_admin')"). A PermissionEvaluator can keep complex ownership and authority checks outside the service expression. Requests from an owner or administrator succeed; an unauthorized user receives HTTP 403. section 11.4 section 11.5

Listing 11.1 Enabling method security
@Configuration
@EnableMethodSecurity
public class ProjectConfig {
}

See the minimal configuration class that enables method security. section 11.1.2

How Spring Security in Action, Second Edition covers it

How deep it goes
Defines annotation placement, defaults, optional switches, and service-level examples, but does not explain framework internals.
Examples
Demonstrates document ownership checks, administrator permissions, HTTP Basic requests, and 403 responses.
What it assumes
Assumes basic Spring configuration and authentication, while introducing method authorization and its annotations.
What you can do after
Apply method authorization with @PreAuthorize, @PostAuthorize, @RolesAllowed, or @Secured.
How it connects
Connects method security with @PreAuthorize, @PostAuthorize, @RolesAllowed, @Secured, SpEL, PermissionEvaluator, and authentication.

Also explained in

Compare how 2 books explain @EnableMethodSecurity →

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.