I have a basic SpringBoot app. using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.
I want to secure a controller
All of @PreAuthorize
, @RolesAllowed
and @Secured
are annotations which allow to configure method security. They can be applied both on individual methods or on class level, in the latter case the security constraints will be applied to all methods in the class.
Method-level security is accomplished using Spring AOP proxies.
@PreAuthorize
@PreAuthorize
annotation allows to specify access constraints to a method using the Spring Expression Language (SpEL). These constraints are evaluated prior to the method being executed and may result in execution of the method being denied if the constraints are not fulfilled. The @PreAuthorize
annotation is part of the Spring Security framework.
In order to be able to use @PreAuthorize
, the prePostEnabled
attribute in the
@EnableGlobalMethodSecurity
annotation needs to be set to true
:
@EnableGlobalMethodSecurity(prePostEnabled=true)
@RolesAllowed
@RolesAllowed
annotation has its origin in the JSR-250 Java security standard. This
annotation is more limited than the @PreAuthorize
annotation because it only supports role-based security.
In order to use the @RolesAllowed
annotation the library containing this annotation needs to be on the classpath, as it is not part of Spring Security. In addition, the jsr250Enabled
attribute of the @EnableGlobalMethodSecurity
annotation need to be set to true
:
@EnableGlobalMethodSecurity(jsr250Enabled=true)
@Secured
@Secured
annotation is a legacy Spring Security 2 annotation that can be used to configure method security. It supports more than only role-based security, but does not support using Spring Expression Language (SpEL) to specify security constraints. It is recommended to use the @PreAuthorize
annotation in new applications over this annotation.
Support for the @Secured
annotation needs to be explicitly enabled in the
@EnableGlobalMethodSecurity
annotation using the securedEnabled
attribute:
@EnableGlobalMethodSecurity(securedEnabled=true)
The following table shows the support for Spring Expression Language in the security annotations that can be used with Spring Security 5:
╔═════════════════════╦═══════════════════╗
║ Security Annotation ║ Has SpEL Support? ║
╠═════════════════════╬═══════════════════╣
║ @PreAuthorize ║ yes ║
╠═════════════════════╬═══════════════════╣
║ @PostAuthorize ║ yes ║
╠═════════════════════╬═══════════════════╣
║ @PreFilter ║ yes ║
╠═════════════════════╬═══════════════════╣
║ @PostFilter ║ yes ║
╠═════════════════════╬═══════════════════╣
║ @Secured ║ no ║
╠═════════════════════╬═══════════════════╣
║ @RolesAllowed ║ no ║
╚═════════════════════╩═══════════════════╝