Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 477
Zack Avatar asked Dec 20 '22 06:12

Zack


2 Answers

@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
like image 123
Bogdan Avatar answered Dec 21 '22 19:12

Bogdan


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

like image 43
vtor Avatar answered Dec 21 '22 19:12

vtor