@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
