Method security in Spring lets you restrict access to individual methods based on the caller's roles or permissions, typically enforced at the service layer.
Key Points: • Enabled via @EnableMethodSecurity (the modern replacement for @EnableGlobalMethodSecurity) on a configuration class. • @PreAuthorize checks permissions before a method runs; @PostAuthorize checks after it returns, useful when the decision depends on the return value. • @Secured is a simpler, role-only alternative that doesn't support SpEL expressions. • Applying security here, rather than only at the controller, protects the logic even if it's called from another internal path. • SpEL expressions in @PreAuthorize can reference method arguments for fine-grained checks.
Example: A service method that deletes a user account can be locked down so only admins can call it, regardless of which controller or scheduled job invokes it.
Code Example:
@Service
public class AccountService {
@PreAuthorize("hasRole('ADMIN')")
public void deleteAccount(Long accountId) {
// deletion logic
}
@PreAuthorize("#userId == authentication.principal.id or hasRole('ADMIN')")
public UserDto getProfile(Long userId) {
// fetch logic
}
}Interview Tip: A concise interview answer is:
"Method security uses annotations like @PreAuthorize and @Secured to enforce role or permission checks directly on service methods, enabled with @EnableMethodSecurity. Putting the checks at the service layer, not just the controller, ensures the rule is enforced no matter how the method gets called."