简体   繁体   中英

When should we use @PreAuthorize and @Secured

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.

@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.

eg @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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM