liveBook · Manning

@RolesAllowed

As explained in Spring Security in Action, Second Edition

@RolesAllowed is a JSR-250 security annotation that restricts access to methods based on the roles assigned to the caller.

@RolesAllowed restricts access to a service method according to the roles assigned to the authenticated caller. Spring Security leaves this annotation disabled until method security enables JSR-250 support. section 11.4

Configure and apply it in two steps:

  • Enable JSR-250 annotations with @EnableMethodSecurity(jsr250Enabled = true). section 11.4
  • Annotate the protected method, such as @RolesAllowed("ADMIN"). section 11.4
  • Prefer @PreAuthorize or @PostAuthorize when authorization requires more expressive rules; @RolesAllowed is less powerful. section 11.4

Role-protected service method

A NameService method annotated with @RolesAllowed("ADMIN") returns its greeting for an authorized caller. Emma receives the greeting, while Natalie receives HTTP 403 when her role does not satisfy the rule. section 11.4

@Service
public class NameService {

 @RolesAllowed("ADMIN")
 public String getName() {
     return "Fantastico";
 }
}

View the minimal service example using @RolesAllowed("ADMIN"). section 11.4

How Spring Security in Action, Second Edition covers it

How deep it goes
Shows enablement and a minimal method example, but defers detailed annotation behavior and favors more powerful authorization expressions.
Examples
Uses NameService.getName(), ADMIN authorization, authenticated curl requests, and successful or HTTP 403 responses.
What you can do after
Operate method security by enabling JSR-250 support and applying role checks to service methods.
How it connects
Connects method security with @EnableMethodSecurity, @Secured, @PreAuthorize, and @PostAuthorize.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Security in Action, Second Edition. The section links point to the parts of the book it draws on.