RolesAllowed vs. PreAuthorize vs. Secured
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
In Java Spring applications, security is a crucial aspect that developers must consider to protect their systems' operations, data, and user information. Spring Security provides several annotations to enforce method security, each with its own characteristics, use cases, and capabilities. This article discusses the @RolesAllowed, @PreAuthorize, and @Secured annotations, focusing on their differences, use cases, and technical implementations.
Annotation Overviews
@RolesAllowed
The `@RolesAllowed` annotation is part of the Java EE security framework and is used to specify role-based access control for Java methods. When using this annotation, only users with the specified roles can invoke the method.
Example usage:
- @RolesAllowed requires the inclusion of `javax.annotation` which might imply using Java EE libraries. It necessitates explicit role management at an application server level.
- @PreAuthorize relies on Spring's security infrastructure, which must be properly configured in the `SecurityConfig` class. It requires enabling the `@EnableGlobalMethodSecurity(prePostEnabled = true)` annotation in your configuration class.
- @Secured needs `@EnableGlobalMethodSecurity(securedEnabled = true)` to be set in the configuration class.
- @RolesAllowed and @Secured are limited to checking the presence of roles. They cannot evaluate expressions or consider attributes of entities or requests.
- @PreAuthorize supports complex expression evaluation. You can use conditions based on request parameters, user attributes, HTTP headers, and more, all of which can dictate access control logic.
- Use @RolesAllowed for applications that are deeply embedded with Java EE principles or when migrating old Java EE apps with simple role checks.
- Use @PreAuthorize for applications that require detailed security logic involving multiple variables or dynamically evaluated conditions.
- Use @Secured for straightforward, role-based validations in Spring applications where complex logic isn't necessary.
Related reading
- Root password inside a Docker container
- running a container with runAsNonRoot and add capabilities
- S3 - Access-Control-Allow-Origin Header
- S3 Bucket Policy to make a specific sub folder public and everything else private?
- Round up double to 2 decimal places
- round up to 2 decimal places in java?
- S3 bucket policy vs access control list
- S3, Signed-URLs and Caching

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.