基于注解方式Spring Security忽略拦截

news2025/7/11 15:28:48

文章目录

  • 1.Spring Security忽略拦截配置
  • 2.基于配置文件注入
    • 2.1.添加配置
    • 2.2.修改Spring Security配置类
    • 2.3. 测试
  • 3.基于注解的方式过滤接口
    • 3.1.添加注解
    • 3.2.获取所有使用了@IgnoreWebSecurity注解的接口访问路径
    • 3.3.测试

1.Spring Security忽略拦截配置

关于Spring Securite的使用可以参考我写的这篇博客: 【SpringBoot框架篇】16.security整合jwt实现对前后端分离的项目进行权限认证

像这种需要忽略某个接口需要在Spring Security配置类中在代码中写死,非常的不灵活。
在这里插入图片描述

2.基于配置文件注入

2.1.添加配置

一般像一些静态资源文件需要过滤掉安全认证,例如图片,.css,.js等静态资源文件,像这种在配置文件中指定比较方便。
application.yml配置

#不需要认证的接口地址
security:
  ignore:
   get:
     - /image/**
   post:

   all:

添加配置类注入配置的参数

@Configuration
@ConfigurationProperties(prefix = "security.ignore")
public class IgnoreSecurityPropetties {

    /**
     * 需要忽略的接口路径 不限制请求类型
     */
    private List<String> all;

    /**
     * 需要忽略的Get请求类型接口路径
     */
    private List<String> get;

    /**
     * 需要忽略的Post请求类型接口路径
     */
    private List<String> post;
    //省略 get,set方法

2.2.修改Spring Security配置类

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 	@Resource
    private IgnoreSecurityPropetties ignoreSecurityPropetties;
    
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {

        String[] all = new String[ignoreSecurityPropetties.getAll().size()];
        String[] get = new String[ignoreSecurityPropetties.getGet().size()];
        String[] post = new String[ignoreSecurityPropetties.getPost().size()];
        ignoreSecurityPropetties.getGet().toArray(get);
        ignoreSecurityPropetties.getPost().toArray(post);
        ignoreSecurityPropetties.getAll().toArray(all);

        if (all.length > 0) {
            authorizeRequest.antMatchers(all).permitAll();
        }
        if (get.length > 0) {
            authorizeRequest.antMatchers(HttpMethod.GET, get).permitAll();
        }
        if (post.length > 0) {
            authorizeRequest.antMatchers(HttpMethod.POST, post).permitAll();
        }
        // 其它接口都要认证
        authorizeRequest.anyRequest().authenticated();

    }
}    

2.3. 测试

@RestController
@RequestMapping("/test")
public class TestIgnoreController {

    @GetMapping("/image/{id}")
    public String image(@PathVariable String id) {
        return id;
    }
}   

在这里插入图片描述

如果从配置文件中删除了过滤的接口名称则访问接口会返回403
在这里插入图片描述

3.基于注解的方式过滤接口

3.1.添加注解

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface IgnoreWebSecurity {

    /**
     * 忽略接口的名称,默认使用Controller访问路径加接口的的访问路径组件 
     * 使用场景匹配url穿参的动态匹配 例如: /user/{id},像这种需要配置注解值为 /user/*
     */
    String value() default "";

}

3.2.获取所有使用了@IgnoreWebSecurity注解的接口访问路径

  • 用到了2.2中的IgnoreSecurityPropetties类存放忽略的接口名称
  • 用到了2.3中的修改security配置类
@Configuration
public class InitIgnoreWebSecurityConfig implements ApplicationContextAware {

    @Autowired
    private IgnoreSecurityPropetties ignoreSecurityPropetties;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        Map<String, Object> beanMap = applicationContext.getBeansWithAnnotation(RestController.class);
        beanMap.forEach((k, v) -> {

            //Controllers配置的访问路径
            String baseUrl = "";
            Class<?> controllerClass = v.getClass();
            RequestMapping annotation = AnnotatedElementUtils.findMergedAnnotation(controllerClass, RequestMapping.class);

            //如果RequestMapping注解存在,使用RequestMapping里配置的路径名称
            if (annotation != null) {
                baseUrl = annotation.value().length > 0 ? annotation.value()[0] : "";
            }

            //判断访问路径前缀是否包含/
            if (!baseUrl.startsWith("/")) {
                baseUrl = "/" + baseUrl;
            }

            //获取所有声明的方法
            Method[] allMethods = controllerClass.getMethods();
            IgnoreWebSecurity ignoreWebSecurity;
            PostMapping postMapping;
            GetMapping getMapping;
            String methodType;

            for (Method method : allMethods) {
                methodType = "";
                //判断方法是否使用忽略权限认证注解
                ignoreWebSecurity = AnnotatedElementUtils.findMergedAnnotation(method, IgnoreWebSecurity.class);
                if (ignoreWebSecurity != null) {
                    String url = "";
                    //当注解没配置接口名称时候使用接口名称(Controller访问路径+接口访问路径)
                    //目前只适配了PostMapping和GetMapping注解,其它类型请自行扩展
                    postMapping = AnnotatedElementUtils.findMergedAnnotation(method, PostMapping.class);
                    if (postMapping != null) {
                        url = postMapping.value().length > 0 ? postMapping.value()[0] : "";
                        methodType = "post";
                    } else {
                        getMapping = AnnotatedElementUtils.findMergedAnnotation(method, GetMapping.class);
                        if (getMapping != null) {
                            url = getMapping.value().length > 0 ? getMapping.value()[0] : "";
                            methodType = "get";
                        }
                    }
                    //注解如果配置了接口路径则使用注解内的
                    if (StringUtils.hasText(ignoreWebSecurity.value())) {
                        url = ignoreWebSecurity.value();
                    }
                    if (url.trim().length() > 0) {
                        url = (baseUrl + "/" + url).replaceAll("/+", "/");
                    } else {
                        url = baseUrl;
                    }
                    if ("post".equals(methodType)) {
                        ignoreSecurityPropetties.getPost().add(url);
                    } else if ("get".equals(methodType)) {
                        ignoreSecurityPropetties.getGet().add(url);
                    }
                }
            }
        });
        System.out.println("需要忽略的get请求类型接口路径如下" );
        for(String get: ignoreSecurityPropetties.getGet()){
            System.out.println(get);
        }
        System.out.println("需要忽略的post请求类型接口路径如下");
        for(String post: ignoreSecurityPropetties.getPost()){
            System.out.println(post);
        }
    }
    
}

启动后会输出
在这里插入图片描述

忽略的接口访问路径规则以下文3.3的测试接口为例,
String baseUrl=@RestController控制器的访问路径(/test)
优先级1: String url=baseUrl+IgnoreWebSecurity(注解内值) =/test/css/*
优先级2: String url=baseUrl+接口访问路径(/login) =/test/login

3.3.测试

在需要忽略认证的接口上面添加@IgnoreWebSecurity注解

@RestController
@RequestMapping("/test")
public class TestIgnoreController {

    @IgnoreWebSecurity("/css/*")
    @GetMapping("/css/{id}")
    public String css(@PathVariable String id) {
        return id;
    }

    @IgnoreWebSecurity
    @GetMapping("/login")
    public String login() {
        return "登录成功";
    }
}

测试用注解修饰的接口路径,可以正常访问,由此可看配置是正常。
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/108833.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

SDL学习

学习笔记&#xff1a;整合安全开发生命周期SDL的Devops工具链建设 分享思路&#xff1a;《SDL安全开发生命周期介绍》 1、什么是SDL&#xff1f; 2、为什么需要SDL&#xff1f; 3、DevSecOps实践&#xff08;SDLDevOps&#xff09; 【整合安全开发生命周期SDL的DevOps工具链建…

408 考研《操作系统》第三章第一节:内存

文章目录教程1. 内存的基础知识1.1什么是内存&#xff1f;有何作用&#xff1f;补充知识&#xff1a;几个常用的数量单位2. 进程的运行原理2.1 指令的工作原理2.2 逻辑地址vs物理地址2.3 从写程序到程序运行2.4 装入模块装入内存2.5 装入的三种方式2.5.1 ——绝对装入2.5.2 ——…

VR的内容荒漠,字节救不了

文|智能相对论 作者|Kinki 去年以来&#xff0c;“元宇宙”概念大火&#xff0c;掀起了新一轮的产业布局和科技博弈&#xff0c;脸书Facebook更直接改名Meta&#xff0c;展示其看好元宇宙未来的决心&#xff0c;国内大厂如腾讯、字节、阿里等&#xff0c;也在游戏、社交、硬件…

Macos安装和卸载第三方软件的正确方法

Mac第三方软件通常指的是非MacApp Store渠道下载安装的应用程序。在Mac电脑中有很多Mac系统内置的软件&#xff0c;但有些用户也喜欢安装一些第三方的软件来提高工作效率&#xff0c;那么我们如何正确的安装和卸载第三方软件呢&#xff1f;教程都在下面哦~ mac第三方软件安装方…

Fabric.js 使用图片遮盖画布(前景图)

本文简介 点赞 关注 收藏 学会了 在 《Fabric.js 使用纯色遮挡画布》 中讲到使用纯色的方式遮盖画布。如果你的常见需要使用图片来遮盖的话&#xff0c;fabric.js 也提供了相应的属性来配置。 相比起使用纯色遮盖画布&#xff0c;使用图片会更复杂。 因为图片本身是有尺寸…

【科研工具】一款好用的科研插件-easyScholar

0.概述1.安装2.功能显示SCI分区&#xff1a;定位优质的文献【看分区排名靠前的1-2区】选中英文按下t翻译&#xff0c;按下y隐藏翻译点击文献网址的图标跳转sci-hub下载0.概述 easyScholar是一款很好用的科研插件&#xff0c;可以显示会议期刊登记&#xff0c;支持轻量翻译&…

SAP OData 服务关于本地文件作为附件上传的一些错误消息

错误消息&#xff1a; {"error": {"code": "005056A509B11EE3AEB5819C07C69E2F","message": {"lang": "en","value": "The server is refusing to process the request because the entity has a…

单机模拟主从复制(一主三从)

引言 操作系统环境&#xff1a;Ubuntu 20.04 Redis版本&#xff1a;6.2.8 准备工作 官网下载 当前最新版本是7.0&#xff0c;我这里用的是6.0&#xff0c;下载 redis-6.2.8.tar.gz&#xff0c;拷贝到自己的虚拟机或者云服务器。 tar -zxvf redis-6.2.8.tar.gz 解压 cd redi…

【HAL库】STM32CubeMX开发----STM32F407----SPI实验

前言 本次实验以 STM32F407VET6 芯片为MCU&#xff0c;使用 25MHz 外部时钟源。 SPI 通信引脚 与 MCU引脚 对应关系如下&#xff1a; SPI接口GPIO端口CS(片选)PA4SCLK(时钟)PA5MISO(数据输入)PA6MOSI(数据输出)PA7 一、使用STM32CubeMX ---- 新建SPI实验工程 步骤1&#xff…

crypto-music is frequency(INS‘hAck CTF 2018)

比较有趣的一题&#xff0c;记录下来。 Music is frequency Passionated by the sound of a nursery rhyme, we decided to build a new way to send private messages. Find a way to decrypt our rsa private key to get your reward. Because we are pretty bad musicians, …

postgres 源码解析46 可见性映射表VM

简介 Postgres 为实现多版本并发控制技术&#xff0c;当事务删除或者更新元组时&#xff0c;并非从物理上进行删除&#xff0c;而是将其进行逻辑删除[具体实现通过设置元组头信息xmax/infomask等标志位信息],随着业务的累增&#xff0c;表会越来越膨胀&#xff0c;对于执行计划…

【QScrollBar | QSlider | QDial | QProgressBar | QLCDNumber】

【QScrollBar | QSlider | QDial | QProgressBar | QLCDNumber】【1】UI设计界面【QScrollBar | QSlider 函数学习】【2】setMinimum | setMaximum【3】setSingleStep【4】setPageStep【5】setValue【6】setSliderPosition【7】setTracking【8】setOrientation【9】setInverted…

C++ :类和对象:文件操作

前言&#xff1a; 程序运行时产生的数据都属于临时数据&#xff0c;程序一旦运行结束&#xff0c;数据都会被释放。通过文件可以 将数据持久化&#xff0c;C 中对文件操作需要包含头文件 <fstream>。 文件类型分为两种&#xff1a; 1&#xff1a;文本文件&#xff1a;文件…

历时9个月重构iNeuOS工业互联网操作系统,打造工业领域的“Office”

目 录 1. 概述... 1 2. 整体介绍... 2 3. 主要功能简介... 5 1. 概述 历时9个月的时间&#xff0c;对iNeuOS工业互联网操作系统进行全面重构&#xff0c;发布内部测试版本。重构的主要目的&#xff1a;工程化的框架优化&#xff0c;更好的聚焦工业领…

35.前端笔记-CSS3-3D转换

1、3D的特点 进大远小物体后面遮挡不可见 x:右为正 y:下为正 z:屏幕外是正&#xff0c;往里是负 3D移动之translate transform:translateX(100px);//仅仅是x轴移动。px或百分比 transform:translateY(100px);//仅仅是y轴移动&#xff0c;px或百分比 transform:translateZ(1…

33页企业内容管理与应用建设整体解决方案

当前企业在采购管理上面临的主要问题总体应对思路利用数字化技术&#xff0c;推动企业采购管理效能与职能升级 基于互联网技术架构推出数字化采购管理平台&#xff0c;帮助企业构建采购过程与供应商管理的两大流程闭环&#xff0c;实现采购过程的在线化协同&#xff0c;进而提升…

华为云大数据BI解决方案,助力企业实现数字化转型

2022年1月12日&#xff0c;国务院印发了《“十四五”数字经济发展规划》&#xff0c;规划明确提出到2025年&#xff0c;数字经济核心产业增加值占国内生产总值比重达到10%。这一规划的出台&#xff0c;充分释放出加快发展数字经济的明确信号&#xff0c;为各行业进行数字化转型…

使用FCN实现语义分割

来源&#xff1a;投稿 作者&#xff1a;王浩 编辑&#xff1a;学姐 这篇文章的核心内容是讲解如何使用FCN实现图像的语义分割。 在文章的开始&#xff0c;我们讲了一些FCN的结构和优缺点。然后&#xff0c;讲解了如何读取数据集。接下来&#xff0c;告诉大家如何实现训练。最后…

Redis跳跃表(SkipList)

什么是跳跃表 跳跃表&#xff08;skiplist&#xff09;是一种有序且随机化的数据结构&#xff0c;它通过在每个节点中维持多个指向其他节点的指针&#xff0c;从而达到快速访问节点的目的。 跳跃表的用处 有序集合(zset)的底层可以采用数组、链表、平衡树等结果来实现, 但是他…

仪表盘读数识别检测 Python+yolov5

仪表读数识别检测利用Pythonyolov5深度学习对仪表盘刻度数进行实时识别检测读取。Python是一种由Guido van Rossum开发的通用编程语言&#xff0c;它很快就变得非常流行&#xff0c;主要是因为它的简单性和代码可读性。它使程序员能够用更少的代码行表达思想&#xff0c;而不会…