zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    SoundTouch
    80211
    netsh wlan
    jest--cmd
    必须精通nuxt了,不可变,to thi
    bili实际的ssr
    vscode 调试vuetify
    【Java】 第四章 异常处理 Notes learn Ma
    Windows 下的符号链接 小示例
    Java 第一二章 配置基础 与 java 数据类型
  • 原文地址:https://www.cnblogs.com/Baker-Street/p/12893414.html
Copyright © 2011-2022 走看看