Spring Security
Java Annotations
Access Control
Authorization
Method Security

RolesAllowed vs. PreAuthorize vs. Secured

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

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.

Course illustration
Course illustration

All Rights Reserved.