Method-Level Security with @PreAuthorize and @Secured in Spring Boot

When building secure applications, it’s not just about securing endpoints—you often need to protect individual methods too. Spring Security provides powerful tools to implement method-level security, primarily using the annotations @PreAuthorize, @PostAuthorize, and @Secured. We’ll walk through how to enable and use Method-Level Security with @PreAuthorize and @Secured in Spring Boot application using the package com.kscodes.springboot.security.

In this tutorial, we’ll focus on the two most commonly used annotations in Spring Boot applications:

  • @PreAuthorize
  • @Secured

Method-Level Security with @PreAuthorize and @Secured in Spring Boot

📌 What is Method-Level Security?

Method-level security allows you to apply access restrictions directly on methods in your codebase, usually in service or controller layers.
This means users will only execute a method if they meet certain authentication or role requirements.

⚙️ Enable Method-Level Security

To begin using @PreAuthorize or @Secured, you need to enable method security in your Spring Boot configuration class.

✅ Add to SecurityConfig.java

🔑 Using @Secured

The @Secured annotation is simple and works well for role-based access control (RBAC).

🎯 Example: Service Layer

Note: Roles must be prefixed with "ROLE_". Spring Security automatically adds this prefix to authorities unless you override it.

🧠 Using @PreAuthorize

@PreAuthorize supports SpEL (Spring Expression Language) and gives you more flexibility.

🎯 Example: Controller with Conditions

💡 Bonus: Method with Custom Condition

🧪 SecurityContext Test Example

When writing tests or debugging method-level security, you can mock authentication like this:

⚖️ Comparison: @Secured vs @PreAuthorize

Feature@Secured@PreAuthorize
Role prefix required✅ Yes (ROLE_)❌ Optional (can use hasRole or hasAuthority)
Supports SpEL❌ No✅ Yes
Multiple roles✅ With array✅ With hasAnyRole()
Fine-grained logic✅ (e.g. match usernames, attributes)

✅ Summary

  • Method-Level Security with @PreAuthorize and @Secured gives precise access control in Spring Boot applications.
  • Use @Secured for simple role-based rules.
  • Use @PreAuthorize for complex, conditional logic using Spring Expression Language.
  • Don’t forget to annotate your config with @EnableMethodSecurity.

🔗 Useful References