区别: @Secured(), @PreAuthorize() 及 @RolesAllowed()

在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的官方参考文档

文章来自:http://www.cnblogs.com/shihuc/p/5051771.html
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3