在Spring security的使用中,為了對方法進行權限控制,通常采用的三個注解,就是@Secured(), @PreAuthorize() 及 @RolesAllowed()。
但是着三者之間的區別,我之前也不是很清楚,現在看看,做個小小的記錄,備忘吧!
現在舉例,比如修改用戶密碼,必須是ADMIN的權限才可以。則可以用下面三種方法:
@Secured({"ROLE_ADMIN"}) public void changePassword(String username, String password); |
@RolesAllowed({"ROLE_ADMIN"}) public void changePassword(String username, String password); |
@PreAuthorize("hasRole('ROLE_ADMIN')") public void changePassword(String username, String password); |
然而,這三個的區別,其實很容易被大家忽視,雖然不是太大的區別。
1. @Secured(): secured_annotation
使用時,需要如下配置Spring Security (無論是通過xml配置,還是在Spring boot下,直接注解配置,都需要指明secured-annotations)
XML: <global-method-security secured-annotations="enabled"/>
Spring boot: @EnableGlobalMethodSecurity(securedEnabled = true)
2. @RolesAllowed(): jsr250-annotations
使用時,需要如下配置Spring Security (無論是通過xml配置,還是在Spring boot下,直接注解配置,都需要指明jsr250-annotations)
XML: <global-method-security jsr250-annotations="enabled"/>
Spring boot: @EnableGlobalMethodSecurity(jsr250Enabled = true)
3. @PreAuthorize(): pre-post-annotations
使用時,需要如下配置Spring Security (無論是通過xml配置,還是在Spring boot下,直接注解配置,都需要指明pre-post-annotations)
XML: <global-method-security pre-post-annotations="enabled"/>
Spring boot: @EnableGlobalMethodSecurity(prePostEnabled = true)
@Secured and @RolesAllowed are the same the only difference is @RolesAllowed is a standard annotation (i.e. not only spring security) whereas @Secured is spring security only.
@PreAuthorize is different in a way that it is more powerful then the other 2. It allows for SpEL expression for a more fine-grained control. Which to use well the simplest thing that could possible work, if you don't need expression etc. go with the standard annotations to limit the dependency on spring classes.
比較方法授權的類型
以下的快速參考表可能在你選擇授權方法檢查時派上用場:
方法授權類型 |
聲明方式 |
JSR標准 |
允許SpEL表達式 |
@PreAuthorize @PostAuthorize |
注解 |
No |
Yes |
@RolesAllowed @PermitAll @DenyAll |
注解 |
Yes |
NO |
@Secure |
注解 |
No |
No |
protect-pointcut |
XML |
No |
No |
尾注:詳細的信息,還是參考Spring的官方參考文檔