• SpringBoot整合SpringSecurity-方法级权限注解


    Spring Security默认是禁用注解的,要想开启注解,要在继承WebSecurityConfigurerAdapter的类加@EnableGlobalMethodSecurity注解,并在该类中将AuthenticationManager定义为Bean

    @Configuration
    @EnableWebSecurity // 启用Spring Security的Web安全支持
    @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true) //开启方法权限注解支持
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        /**
         * Spring Security默认是禁用注解的,要想开启注解,要在继承WebSecurityConfigurerAdapter的类加@EnableGlobalMethodSecurity注解,
         * 并在该类中将AuthenticationManager定义为Bean。
         * @return
         * @throws Exception
         */
        @Bean
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }

    @EnableGlobalMethodSecurity 分别有prePostEnabled 、securedEnabledjsr250Enabled 三个字段,其中每个字段代码一种注解支持,默认为false,true为开启

    1.JSR-250注解

    导入坐标

    <!--JSR250:security权限注解-->
                <dependency>
                    <groupId>javax.annotation</groupId>
                    <artifactId>jsr250-api</artifactId>
                    <version>1.0</version>
                </dependency>

    在指定方法中使用方法注解@RolesAllowed,@DenyAll,@PermitAll

    @DenyAll 和 @PermitAll 代表全部拒绝和全部通过
    
    @RolesAllowed({"USER", "ADMIN"})
    代表标注的方法只要具有USER, ADMIN任意一种权限就可以访问。这里可以省略前缀ROLE_,实际的权限可能是ROLE_ADMIN。

    2.securedEnabled注解

    @Secured("ROLE_ADMIN")
    @Secured({ "ROLE_DBA", "ROLE_ADMIN" })

    3.prePostEnabled注解(支持表达式)

    主要注解

    @PreAuthorize --适合进入方法之前验证授权

    @PostAuthorize --检查授权方法之后才被执行

    @PostFilter --在方法执行之后执行,而且这里可以调用方法的返回值,然后对返回值进行过滤或处理或修改并返回

    @PreFilter --在方法执行之前执行,而且这里可以调用方法的参数,然后对参数值进行过滤或处理或修改

    @PreAuthorize("authentication.principal.username == 'tom' ")
    @PreAuthorize("hasRole('ROLE_ADMIN')")

    另外该注解还支持自定义匹配器,详细配置可见链接:https://blog.csdn.net/qq_32867467/article/details/95078794

  • 相关阅读:
    iOS uiscrollView 嵌套 问题 的解决
    NSURLConnection 网络超时的那些事(转别人整理的)
    IOS 开发中判断NSString是否为空字符
    iOS- SQLite3的基本使用
    怎么应对 domino文档损坏然后损坏文档别删除导致数据丢失
    为什么Log.nsf中存储的日志只有最近7天的原因
    Struts,Spring,Hibernate优缺点
    Java面试之List的三个子类ArrayList,LinkedList,Vector区别
    Java面试之同步/异步/阻塞/非阻塞/BIO/NIO/AIO
    如何设置 Windows 开机启动项
  • 原文地址:https://www.cnblogs.com/Baker-Street/p/12893414.html
Copyright © 2020-2023  润新知