zoukankan      html  css  js  c++  java
  • 区别: @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的官方参考文档

  • 相关阅读:
    (创建型模式)Abstract Factory——抽象工厂模式
    (结构型模式)Composite——组合模式
    (行为模式)Command——命令模式
    (创建型模式)Singleton——单例模式
    Windows的Notepad++的插件
    Ubuntu的软件源更新常见问题及解决
    The following signatures were invalid: BADSIG 40976EAF437D05B5 Ubuntu Archive Automatic Signing Key
    Ubuntu安装ImageMagick
    常见误操作之警惕
    Rails3.2.x new project启动错误:Could not find a JavaScript runtime.
  • 原文地址:https://www.cnblogs.com/jpfss/p/8668228.html
Copyright © 2011-2022 走看看