Can you explain how to use method-level security in Spring Boot?

Method-level security lets you attach access rules directly to individual service or controller methods using annotations, giving finer-grained control than URL-based rules alone.

Key Points: • Enable it with @EnableMethodSecurity (the modern replacement for @EnableGlobalMethodSecurity) on a configuration class. • @PreAuthorize evaluates a SpEL expression before the method executes, blocking the call if it fails. • @PostAuthorize checks conditions after the method runs, useful when the decision depends on the returned object. • @Secured offers a simpler, role-list-only alternative without SpEL expressiveness. • Method security composes well with URL security—URL rules provide a coarse first gate, methods enforce precise business rules.

Example: A deleteUser() service method is annotated so only an ADMIN can invoke it, even if it's called internally from another service rather than directly through a controller.

Code Example:

@EnableMethodSecurity
@Configuration
public class MethodSecurityConfig {}

@Service
public class UserService {

    @PreAuthorize("hasRole('ADMIN')")
    public void deleteUser(Long userId) {
        // deletion logic
    }
}

Interview Tip: A concise interview answer is:

"I enable method-level security with @EnableMethodSecurity, then annotate individual service methods with @PreAuthorize using SpEL expressions like hasRole('ADMIN'). This protects the method itself regardless of how it's invoked, which is more robust than relying only on URL-based rules at the controller boundary."