• 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

  • 相关阅读:
    oracle-报错 RMAN-03002,RMAN-06172
    oracle--报错 ORA-01003,ORA-09817,ORA-01075
    oracle--报错 ORA-00257
    Linux-iostat命令
    oracle--查询速度慢
    linux-根目录添加内存
    mysq-5.7忘记密码修改
    zsh: command not found cnpm,gulp等命令在zsh终端上报错的问题
    vue中的js引入图片,必须require进来
    如何启动一个Vue3.x项目
  • 原文地址:https://www.cnblogs.com/Baker-Street/p/12893414.html
Copyright © 2020-2023  润新知