Method-Level Security with PreAuthorize

Learn method-level security in Spring Boot using @PreAuthorize, @PostAuthorize, SpEL expressions, roles, permissions, ownership checks, and service-layer authorization.

What You Will Learn

  • Why service-layer authorization matters.
  • How to enable method security.
  • How to use @PreAuthorize.
  • How to check roles, permissions, and ownership.
  • Common mistakes in method-level security.

Introduction

URL security protects endpoints. Method-level security protects business operations.

This is important because multiple controllers, jobs, listeners, or APIs may call the same service method.

Enable Method Security

@Configuration
@EnableMethodSecurity
public class SecurityConfig {
}

Role-Based Check

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

Permission-Based Check

@PreAuthorize("hasAuthority('POLICY_WRITE')")
public void updatePolicy(UpdatePolicyRequest request) {
    // update policy
}

Ownership Check

@PreAuthorize("#accountId == authentication.principal.accountId")
public AccountDetails getAccount(Long accountId) {
    return accountRepository.findById(accountId).orElseThrow();
}

Custom Authorization Bean

@PreAuthorize("@policySecurity.canViewPolicy(authentication, #policyId)")
public PolicyDto getPolicy(Long policyId) {
    return policyService.load(policyId);
}

Authorization Flow

flowchart TD
    A["Controller calls service"] --> B["@PreAuthorize"]
    B --> C["Evaluate expression"]
    C --> D{"Allowed?"}
    D -->|Yes| E["Run method"]
    D -->|No| F["AccessDeniedException"]

Best Practices

  • Prefer permissions for complex systems.
  • Keep expressions readable.
  • Move complex checks to a bean.
  • Test authorization rules.
  • Never rely only on UI hiding.

Summary

Method-level security protects business operations where they actually happen. Use it with URL security for defense in depth.

Learning Path Navigation

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.