Answers:
真正的区别是@PreAuthorize
可以与Spring Expression Language(SpEL)一起使用。您可以:
SecurityExpressionRoot
。访问方法参数(需要使用debug info或custom进行编译ParameterNameDiscoverer
):
@PreAuthorize("#contact.name == principal.name")
public void doSomething(Contact contact)
MethodSecurityExpressionHandler
并将其设置为<global-method-security><expression-handler ... /></...>
)。@PreAuthorize
是不同的,它比强大@Secured
。
较早的
@Secured
注释不允许使用表达式。
从Spring Security 3开始,首选更灵活的注释
@PreAuthorize
和@PostAuthorize
(以及@PreFilter和@PostFilter),因为它们支持Spring Expression Language(SpEL)并提供基于表达式的访问控制。
@Secured("ROLE_ADMIN")
注释与相同@PreAuthorize ("hasRole('ROLE_ADMIN')")
。
将
@Secured({"ROLE_USER","ROLE_ADMIN")
被视为ROLE_USER OR ROLE_ADMIN。
因此您无法使用来表达AND条件
@Secured。您可以使用定义相同的名称
@PreAuthorize("hasRole('ADMIN') OR hasRole('USER')")
,这更容易理解。您也可以表达AND,OR或NOT(!)。@PreAuthorize(“!isAnonymous()AND hasRole('ADMIN')”)
"hasRole('ADMIN OR hasRole('USER')"
吗?
+-----------------------------------------------+----------------------------------------------------------+-----------------------------------------------------------------+
| | @Secured | @PreAuthorize |
+-----------------------------------------------+----------------------------------------------------------+-----------------------------------------------------------------+
| Spring EL expressions | Does'nt supports. | Supports |
+-----------------------------------------------+----------------------------------------------------------+-----------------------------------------------------------------+
| Multiple roles conjunctions with AND operator | Does'nt supports.(If there are multiple roles defined | Supports |
| |they will be automatically combined with OR operator) | |
+-----------------------------------------------+----------------------------------------------------------+-----------------------------------------------------------------+
| To enable annotation | Add following line to spring-security.xml | Add following line to spring-security.xml |
| | <global-method-security secured-annotations="enabled" /> | <global-method-security pre-post-annotations="enabled"/> |
+-----------------------------------------------+----------------------------------------------------------+-----------------------------------------------------------------+
| Example | @Secured({ROLE_ADMIN , ROLE_USER}) | @PreAuthorize("hasRole('ROLE_USER') and hasRole('ROLE_ADMIN')") |
| | public void addUser(UserInfo user){...} | public void addUser(UserInfo user){...} |
+-----------------------------------------------+----------------------------------------------------------+-----------------------------------------------------------------+