Can you describe the configuration steps necessary for method-level security?

Method-level security lets you enforce authorization rules directly on service or controller methods using annotations, rather than only at the URL level, giving finer-grained control over who can invoke specific business operations.

Key Points: • @EnableMethodSecurity (or the older @EnableGlobalMethodSecurity) on a configuration class activates annotation-driven method security. • @PreAuthorize evaluates a SpEL expression before the method runs, and @PostAuthorize checks the return value after execution. • @Secured and @RolesAllowed offer simpler, role-based alternatives when SpEL flexibility isn't needed. • A SecurityFilterChain (or, in older versions, a class extending WebSecurityConfigurerAdapter) still needs to define authentication and the overall security rules that method security builds on top of. • The security context must be populated with the authenticated user's roles/authorities for these annotations to have anything to evaluate.

Example: Annotating a deleteUser(id) service method with @PreAuthorize("hasRole('ADMIN')") ensures the method throws an AccessDeniedException if a non-admin user's request somehow reaches it, even if a URL-level check was missed upstream.

Code Example:

@Configuration
@EnableMethodSecurity
public class MethodSecurityConfig {
}

@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) {
    userRepository.deleteById(id);
}

Interview Tip: A concise interview answer is:

"I enable it with @EnableMethodSecurity on a config class, then annotate individual methods with @PreAuthorize or @Secured to declare the required roles or expressions. This gives defense in depth — even if a URL-level rule is missed, the method itself refuses to execute for an unauthorized caller."