@Secured Annotation in Spring Security
@Secured is Spring Security's original method security annotation. It takes a list of authority names, and the annotated method may only be called by a user who has at least one of them. There are no expressions, no arguments and no bean calls: just "who may call this".
That simplicity is both its strength and its limit. This tutorial explains how @Secured is enabled and evaluated, the rule about full authority names that catches many developers, how class-level annotations combine with method-level ones, and when to move to @PreAuthorize. The example is a warehouse inventory service.
1. What Is @Secured?
@Secured lives in org.springframework.security.access.annotation. Its value is an array of strings. Spring Security's SecuredAuthorizationManager grants access when the current user holds any of the listed authorities. The comparison is exact: @Secured("ROLE_MANAGER") matches the authority ROLE_MANAGER, and no prefix is added for you.
It is disabled by default. Turn it on with @EnableMethodSecurity(securedEnabled = true). Like every method security annotation, it is enforced by a Spring proxy, as explained in method-level security.
2. Why Use @Secured?
- Readable role lists.
@Secured({"ROLE_CLERK", "ROLE_MANAGER"})needs no knowledge of SpEL. - Compile-time friendly. Authority names can be constants, so a typo becomes a compile error rather than a silent denial.
- Existing code. Many older Spring applications use it, and it remains fully supported.
It cannot express conditions on arguments or return values, combine rules with and, or call beans. For those, use @PreAuthorize.
3. How @Secured Is Evaluated
| Annotation value | Matches the authority | Notes |
|---|---|---|
@Secured("ROLE_MANAGER") | ROLE_MANAGER | Correct way to require a role |
@Secured("MANAGER") | MANAGER | Usually a mistake: users built with roles("MANAGER") do not match |
@Secured({"ROLE_CLERK", "ROLE_MANAGER"}) | Either one | Any-of semantics; there is no "all of" |
@Secured("inventory:export") | inventory:export | Works for permission-style authorities too |
4. A Complete Example: Warehouse Inventory
Stock clerks look up stock levels, warehouse managers see write-off reports, an export requires a dedicated permission, and auditors have their own service. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2. Authority names are kept in a constants class so the compiler catches typos.
package com.javabytechie.warehouse;
public final class Authorities {
public static final String CLERK = "ROLE_STOCK_CLERK";
public static final String MANAGER = "ROLE_WAREHOUSE_MANAGER";
public static final String AUDITOR = "ROLE_AUDITOR";
public static final String EXPORT = "inventory:export";
private Authorities() {
}
}
package com.javabytechie.warehouse;
import java.util.List;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
@Service
public class InventoryService {
@Secured({Authorities.CLERK, Authorities.MANAGER}) // either role
public String stockLevel(String sku) {
return sku + ": 148 units in aisle 12";
}
@Secured(Authorities.MANAGER)
public List<String> writeOffReport() {
return List.of("SKU-310 water damage: 12 units");
}
@Secured(Authorities.EXPORT) // a permission, not a role
public String exportInventory() {
return "sku,units\nSKU-881,148\nSKU-310,40";
}
}
package com.javabytechie.warehouse;
import java.util.List;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
@Service
@Secured(Authorities.AUDITOR) // applies to every method by default
public class AuditService {
public List<String> stockMovements() {
return List.of("SKU-881 +200 (receiving)", "SKU-881 -52 (orders)");
}
@Secured({Authorities.AUDITOR, Authorities.MANAGER}) // replaces the class rule
public String monthlySummary() {
return "November: 3 write-offs, 0 discrepancies";
}
}
package com.javabytechie.warehouse;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WarehouseController {
private final InventoryService inventory;
private final AuditService audit;
public WarehouseController(InventoryService inventory, AuditService audit) {
this.inventory = inventory;
this.audit = audit;
}
@GetMapping("/api/stock/write-off-report")
public List<String> writeOffs() { return inventory.writeOffReport(); }
@GetMapping("/api/stock/{sku}")
public String stock(@PathVariable String sku) { return inventory.stockLevel(sku); }
@GetMapping("/api/exports/inventory")
public String export() { return inventory.exportInventory(); }
@GetMapping("/api/audit/movements")
public List<String> movements() { return audit.stockMovements(); }
@GetMapping("/api/audit/summary")
public String summary() { return audit.monthlySummary(); }
}
package com.javabytechie.warehouse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/error").permitAll()
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
UserDetailsService users(PasswordEncoder encoder) {
// Demo staff only
return new InMemoryUserDetailsManager(
User.withUsername("kamal").password(encoder.encode("kamal-pass"))
.authorities(Authorities.CLERK).build(),
User.withUsername("rina").password(encoder.encode("rina-pass"))
.authorities(Authorities.MANAGER, Authorities.EXPORT).build(),
User.withUsername("olu").password(encoder.encode("olu-pass"))
.authorities(Authorities.AUDITOR).build());
}
}
package com.javabytechie.warehouse;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WarehouseApplication {
public static void main(String[] args) {
SpringApplication.run(WarehouseApplication.class, args);
}
}
5. Step-by-Step Code Explanation
securedEnabled = trueregisters the interceptor for@Secured. Without it, every method in this example would be open to any logged-in user.- Constants with full names.
Authorities.MANAGERisROLE_WAREHOUSE_MANAGER, including the prefix, because@Securedcompares exact strings. The same constants are used when creating the users. - Any-of lists.
stockLevelaccepts clerks or managers. - A permission.
exportInventoryrequiresinventory:export, which only Rina has, regardless of roles. - Class and method levels.
AuditServiceis restricted to auditors at class level.monthlySummarydeclares its own list, which replaces the class rule rather than adding to it.
6. Expected Output
$ curl -u kamal:kamal-pass localhost:8080/api/stock/SKU-881
HTTP/1.1 200
SKU-881: 148 units in aisle 12
$ curl -u kamal:kamal-pass localhost:8080/api/stock/write-off-report
HTTP/1.1 403
{"timestamp":"2026-11-18T12:14:57.237Z","status":403,"error":"Forbidden","path":"/api/stock/write-off-report"}
$ curl -u rina:rina-pass localhost:8080/api/stock/write-off-report
HTTP/1.1 200
["SKU-310 water damage: 12 units"]
$ curl -u rina:rina-pass localhost:8080/api/exports/inventory
HTTP/1.1 200
sku,units
SKU-881,148
SKU-310,40
$ curl -u kamal:kamal-pass localhost:8080/api/exports/inventory
HTTP/1.1 403
{"timestamp":"2026-11-18T12:14:57.448Z","status":403,"error":"Forbidden","path":"/api/exports/inventory"}
$ curl -u olu:olu-pass localhost:8080/api/audit/movements
HTTP/1.1 200
["SKU-881 +200 (receiving)","SKU-881 -52 (orders)"]
$ curl -u rina:rina-pass localhost:8080/api/audit/movements
HTTP/1.1 403
{"timestamp":"2026-11-18T12:14:57.581Z","status":403,"error":"Forbidden","path":"/api/audit/movements"}
$ curl -u rina:rina-pass localhost:8080/api/audit/summary
HTTP/1.1 200
November: 3 write-offs, 0 discrepancies
Kamal reads stock levels but cannot see write-offs or export. Rina, a manager with the export permission, can do both. Olu, the auditor, reads stock movements through the class-level rule, while Rina is refused there. The monthly summary has its own method-level rule that also admits managers, so Rina may read it.
7. Advantages and Limitations
| Advantages | Limitations |
|---|---|
| Simple, declarative role lists | No expressions, arguments, return values or bean calls |
| Constants give compile-time checking of names | No "all of these" rule; only any-of |
| Works for roles and permission-style authorities | Full authority names required; easy to forget ROLE_ |
| Long-standing and widely understood | Must be enabled explicitly with securedEnabled |
8. When to Choose @Secured
@Secured is a sound choice when every rule in a service is a plain list of roles or permissions and is likely to stay that way, for example an internal back-office tool with a handful of fixed roles. Keeping authority names in constants, as in the example, gives you compile-time checking that string expressions cannot offer.
Choose @PreAuthorize instead as soon as a rule depends on who owns the data, on method arguments or on more than one condition. In a new project, most teams standardise on @PreAuthorize from the start so that every rule is written the same way.
9. Migrating from @Secured to @PreAuthorize
Teams often start with @Secured and later need a condition that it cannot express. The translation is mechanical, so it can be done one method at a time. Remember that hasRole adds the prefix, so ROLE_ disappears from role names, while permission-style authorities move to hasAuthority or hasAnyAuthority unchanged:
| @Secured | Equivalent @PreAuthorize |
|---|---|
@Secured("ROLE_WAREHOUSE_MANAGER") | @PreAuthorize("hasRole('WAREHOUSE_MANAGER')") |
@Secured({"ROLE_STOCK_CLERK", "ROLE_WAREHOUSE_MANAGER"}) | @PreAuthorize("hasAnyRole('STOCK_CLERK', 'WAREHOUSE_MANAGER')") |
@Secured("inventory:export") | @PreAuthorize("hasAuthority('inventory:export')") |
| Not possible | @PreAuthorize("hasRole('STOCK_CLERK') and #sku.startsWith('SKU-')") |
After migrating the last @Secured method, remove securedEnabled = true so the unused interceptor is no longer registered. Run your security tests before and after; a forgotten prefix shows up immediately as a 403 in a test that expected 200.
10. Common Mistakes and Best Practices
- Forgetting
securedEnabled = true. The annotation compiles and is silently ignored. - Writing
@Secured("ADMIN"). Use the full authority,ROLE_ADMIN. - Expecting class and method rules to combine. The method-level annotation replaces the class-level one.
- Mixing annotation styles on one method. Spring Security rejects more than one method security annotation of the same kind on a method; keep one style per method.
- Plan for growth. When a rule needs a condition, move it to
@PreAuthorize("hasAnyRole('CLERK', 'MANAGER')")and continue from there. The @RolesAllowed page compares the standard Jakarta alternative.
11. Summary
@Securedrestricts a method to users holding any of the listed authorities.- Enable it with
@EnableMethodSecurity(securedEnabled = true). - It compares exact strings, so roles must be written with the
ROLE_prefix. - A method-level
@Securedreplaces the class-level one. - Use
@PreAuthorizewhen you need expressions, arguments or bean calls.
12. References
Frequently Asked Questions (FAQ)
Q1. How do I enable @Secured in Spring Boot?
Add @EnableMethodSecurity(securedEnabled = true) to a configuration class. @Secured is disabled by default.
Q2. Does @Secured add the ROLE_ prefix?
No. It compares exact authority strings, so write @Secured("ROLE_ADMIN"). @RolesAllowed, by contrast, adds the prefix for you.
Q3. Can @Secured require several roles at once?
No. A list such as @Secured({"ROLE_A", "ROLE_B"}) means either role is enough. To require both, use @PreAuthorize("hasRole('A') and hasRole('B')").
Q4. What is the difference between @Secured and @PreAuthorize?
@Secured lists authority names only. @PreAuthorize takes a SpEL expression that can combine conditions, inspect arguments and call beans, and it is enabled by default with @EnableMethodSecurity.
Q5. Can I use @Secured on a class?
Yes. A class-level @Secured applies to all public methods of the bean. A method that declares its own @Secured uses only its own list.