I read this stackoverflow post What's the difference between @Secured and @PreAuthorize in spring security 3? However,I am still not clear as to what is the big difference between the two in terms of security? In what scenarios should we go for @PreAuthorize as compared to @Secured?
@PreAuthorize
allows you to get a more fine-grained control on the rules to secure o method. You can use SpEL expression inside of it.
Securing a method with @Secured
gives you the same result as @PreAuthorize
but the @Secured
is limited and you don't get as much options to tweak the rules (a gross simplification it's that the rules are "static").
Spring Security 3.0 introduced the ability to use Spring EL expressions as an authorization mechanism in addition to the simple use of configuration attributes and access-decision voters which have seen before. Expression-based access control is built on the same architecture but allows complicated boolean logic to be encapsulated in a single expression.
- http://docs.spring.io/spring-security/site/docs/3.0.x/reference/el-access.html
@PreAuthorize
is a newer version, so you should always go with @PreAuthorize
, which is indeed better for the reasons mentioned here.
And in fact
@Secured("ROLE_ADMIN")
is identical to @PreAuthorize("hasRole('ROLE_ADMIN')")
In addition, @PreAuthorize syntax is more readable.
e.g.
@Secured({"ROLE_USER", "ROLE_ADMIN"})
is treated as ROLE_USER
or
ROLE_ADMIN
, which is something weird and confusing.
On the other side with @PreAuthorize
you use the "Spring Expression Language (SpEL)" where you define explicitly or
, and
expressions, which is obviously convenient and more readable.
So go with @PreAuthorize
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With