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

news/2024/10/25 3:26:52/

文章目录

  • 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 {@Resourceprivate IgnoreSecurityPropetties ignoreSecurityPropetties;@Overrideprotected 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 {@Autowiredprivate IgnoreSecurityPropetties ignoreSecurityPropetties;@Overridepublic 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.ppmy.cn/news/5809.html

相关文章

Flarum部署:从源码到docker到放弃

警告&#xff1a; 此篇文章前半段记录了我用代码部署flarum遇到的一些问题和解决办法&#xff0c;但是可能是由于我是在不熟悉php的框架结构&#xff0c;最终我还是选择了使用docker进行部署&#xff0c;请斟酌是否继续阅读本文。 Hello&#xff0c;大家好&#xff0c;我是内网…

IU酒店释放轻中端投资活力,开启曲靖酒店新篇章

曲靖位于云南省东北部&#xff0c;是云南连接内地的重要陆路通道&#xff0c;素有“滇黔锁钥”、“入滇门户”、“云南咽喉”之称&#xff0c;是仅次于昆明的云南第二大城市。曾入选“中国十佳宜居城市”榜单10次的城市&#xff0c;拥有3000多年的文明史&#xff0c;早在三国魏…

通过脚手架vue-cli创建一个vue项目

我需要在vue-demo文件下新建vue项目 步骤一 ①在该文件夹下打开集成终端 输入创建命令 命令 vue create 项目名称 &#xff0c;注意不要使用驼峰命名法 如果是第一次配置&#xff0c;有面的提示&#xff0c;这里说你这样速度会很慢的&#xff0c;用不用镜像啊&#xff0c;这…

基于HOG、LBP完成特征工程,基于SVM/RF/XGBOOST/GBDT/CNN/DNN完成人脸识别+表情识别

在我之前的文章中写过很多关于人脸识别和表情识别的文章&#xff0c;今天有一个项目的需求就是需要做两种或者是多种任务&#xff0c;我在开发完对应的模型之后就突然想到了之前做过的人脸识别和表情识别的项目&#xff0c;就想着是否可以基于机器学习/深度学习等方式来同时实现…

打造飞一样的前端:vue3应用打包优化

目录前言优化vue3构建的几点措施采用CDN压缩JS按需加载按需加载vxe-table按需加载element-plus总结前言 vue3应用上线后&#xff0c;一直受困于加载过慢&#xff0c;昨天终于坐下来做些优化。本想切换到webpack打包&#xff0c;但还是坚持了vite。 优化vue3构建的几点措施 采…

Hook原理

对于会Hook的人来说,Hook其实也就那么回事.对于没有Hook过的人来说,会感觉Hook很高大上(其实也没毛病). 那么今天我们就来探讨一些Hook的原理是什么. 我认为任何Hook都可以分为以下三步(简称WFH): 需要Hook的是什么,在哪里(后面简称Where). 寻找到Hook的地方.(后面简称Find)…

【用户交互】

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 前言一、用户交互3.1 函数返回码3.2 常用3.3 acedGetXXX函数3.3.1 常规3.3.2 acedInitGet3.3.3 选择实体3.4 选择集3.4.1 常用函数3.4.2 acedSSGet函数详解总结前言 本文就介绍了用户交互内容。 提…

Python基础知识入门(四)

Python基础知识入门&#xff08;一&#xff09; Python基础知识入门&#xff08;二&#xff09; Python基础知识入门&#xff08;三&#xff09; 一、条件控制 条件语句是通过一条或多条语句的执行结果&#xff08;True 或者False&#xff09;来决定执行的代码块。 注意&…