最新版Spring Security中的路径匹配方案

 更新时间:2024年04月22日 11:49:45   作者:江南一点雨  
在 Spring Security 中,路径匹配是权限控制的核心部分,它决定了哪些请求可以访问特定的资源,本文将详细介绍 Spring Security 中的路径匹配策略,并提供相应的代码示例,需要的朋友可以参考下

Spring Security 是一个功能强大且可高度定制的安全框架,它提供了一套完整的解决方案,用于保护基于 Spring 的应用程序。在 Spring Security 中,路径匹配是权限控制的核心部分,它决定了哪些请求可以访问特定的资源。本文将详细介绍 Spring Security 中的路径匹配策略,并提供相应的代码示例。

在旧版的 Spring Security 中,路径匹配方法有很多,但是新版 Spring Security 对这些方法进行了统一的封装,都是调用 requestMatchers 方法进行处理:

public C requestMatchers(RequestMatcher... requestMatchers) {
	Assert.state(!this.anyRequestConfigured, "Can't configure requestMatchers after anyRequest");
	return chainRequestMatchers(Arrays.asList(requestMatchers));
}

requestMatchers 方法接收一个 RequestMatcher 类型的参数,RequestMatcher 是一个接口,这个接口是一个用来确定 HTTP 请求是否与给定的模式匹配的工具。这个接口提供了一种灵活的方式来定义请求的匹配规则,从而可以对不同的请求执行不同的安全策略。

所以在新版 Spring Security 中,不同的路径匹配分方案实际上就是不同的 RequestMatcher 的实现类。

1. AntPathRequestMatcher

AntPathRequestMatcher 是 Spring 中最常用的请求匹配器之一,它使用 Ant 风格的路径模式来匹配请求的 URI。

1.1 什么是 Ant 风格的路径模式

Ant 风格的路径模式(Ant Path Matching)是一种用于资源定位的模式匹配规则,它源自 Apache Ant 这个 Java 构建工具。在 Ant 中,这种模式被用来指定文件系统中的文件和目录。由于其简单性和灵活性,Ant 风格的路径模式也被其他许多框架和应用程序所采用,包括 Spring Security。

Ant 风格的路径模式使用了一些特殊的字符来表示不同级别的路径匹配:

  • ?:匹配任何单个字符(除了路径分隔符)。

  • *:匹配任何字符的序列(除了路径分隔符),但不包括空字符串。

  • **:匹配任何字符的序列,包括空字符串。至少匹配一个字符的序列,并且可以跨越路径分隔符。

  • {}:表示一个通配符的选择,可以匹配多个逗号分隔的模式。例如,{,春夏秋冬} 可以匹配任何以春夏秋冬开头的字符串。

  • []:在某些实现中,可以用于匹配括号内的单个字符。

  • ():在某些实现中,可以用于分组匹配。

在 Spring Security 中,Ant 风格的路径模式通常用于定义 URL 路径和安全配置之间的映射关系。例如,你可以使用 Ant 风格的路径模式来指定哪些 URL 路径需要特定的权限或角色。

以下是一些 Ant 风格路径模式的例子:

  • /users/*:匹配以 /users/ 开始的任何路径,如 /users/123/users/profile

  • /users/**:匹配以 /users/ 开始的任何路径,包括子路径,如 /users/123/users/profile/picture.

  • /users/123:精确匹配 /users/123

  • /users/{id}:虽然这不是 Ant 风格的模式,但它展示了路径参数匹配,可以匹配 /users/123/users/456 等。

  • /files/**.{jpg,png}:匹配 /files/ 下所有以 .jpg.png 结尾的文件路径,如 /files/image1.jpg/files/folder/image.png

通过使用 Ant 风格的路径模式,你可以灵活地定义复杂的 URL 匹配规则,以适应不同的安全需求。

1.2 基本用法

import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

// 创建 AntPathRequestMatcher 实例
RequestMatcher antMatcher = new AntPathRequestMatcher("/users/**", "GET");

// 使用 matcher 进行匹配
boolean isMatch = antMatcher.matches(request);

1.3 通配符

  • ? 匹配任何单字符。
  • * 匹配任何字符序列(但不包括目录分隔符)。
  • ** 匹配任何字符序列,包括目录分隔符。
// 匹配 /admin 下的任何资源,包括子目录
RequestMatcher adminMatcher = new AntPathRequestMatcher("/admin/**");

// 匹配 /files 目录下的任何 HTML 文件
RequestMatcher fileMatcher = new AntPathRequestMatcher("/files/*.{html,htm}", "GET");

2. RegexRequestMatcher

RegexRequestMatcher 使用正则表达式来匹配请求的 URI 和 HTTP 方法。

2.1 基本用法

import org.springframework.security.web.util.matcher.RegexRequestMatcher;

// 创建 RegexRequestMatcher 实例
RequestMatcher regexMatcher = new RegexRequestMatcher("^/api/.*", "GET");

// 使用 matcher 进行匹配
boolean isMatch = regexMatcher.matches(request);

2.2 使用正则表达式

// 匹配任何以 /api 开头的 URI
RequestMatcher apiMatcher = new RegexRequestMatcher("^/api/.*");

// 匹配任何 HTTP 方法
RequestMatcher anyMethodMatcher = new RegexRequestMatcher("^/.*", "GET|POST|PUT|DELETE");

2.3 结合 Spring Security

下面这段代码,表示拦截所有以 html、css 以及 js 结尾的请求,这些请求可以直接访问:

@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(a -> a.requestMatchers(new RegexRequestMatcher("^.*\\.(htm|css|js)$","GET")).permitAll())
                .formLogin(Customizer.withDefaults())
                .csrf(c -> c.disable());
        return http.build();
    }
}

3. RequestHeaderRequestMatcher

RequestHeaderRequestMatcher 用来匹配请求头中的键和值。

import org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher;

// 创建 RequestHeaderRequestMatcher 实例
RequestMatcher headerMatcher = new RequestHeaderRequestMatcher("User-Agent", "Mozilla.*");

// 使用 matcher 进行匹配
boolean isMatch = headerMatcher.matches(request);

具体到 Spring Security 中,用法如下:

@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(a -> a.requestMatchers(new RequestHeaderRequestMatcher("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36")).permitAll())
                .formLogin(Customizer.withDefaults())
                .csrf(c -> c.disable());
        return http.build();
    }
}

4. NegatedRequestMatcher

NegatedRequestMatcher 允许你否定一个已有的 RequestMatcher 的匹配结果。

import org.springframework.security.web.util.matcher.NegatedRequestMatcher;

// 创建一个 matcher,然后否定它的匹配结果
RequestMatcher notAdminMatcher = new NegatedRequestMatcher(adminMatcher);

// 使用 negated matcher 进行匹配
boolean isNotMatch = notAdminMatcher.matches(request);

例如下面这段代码表示除了 /hello 之外的地址,全都可以直接访问:

@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(a -> a.requestMatchers(new NegatedRequestMatcher(new AntPathRequestMatcher("/hello"))).permitAll())
                .formLogin(Customizer.withDefaults())
                .csrf(c -> c.disable());
        return http.build();
    }
}

5. AndRequestMatcher 和 OrRequestMatcher

AndRequestMatcherOrRequestMatcher 分别用来组合多个 RequestMatcher 实例,进行“与”或“或”的逻辑匹配。

5.1 AndRequestMatcher

import org.springframework.security.web.util.matcher.AndRequestMatcher;

// 组合多个 matcher 进行“与”匹配
RequestMatcher andMatcher = new AndRequestMatcher(apiMatcher, headerMatcher);

// 使用 andMatcher 进行匹配
boolean isMatch = andMatcher.matches(request);

5.2 OrRequestMatcher

import org.springframework.security.web.util.matcher.OrRequestMatcher;

// 组合多个 matcher 进行“或”匹配
RequestMatcher orMatcher = new OrRequestMatcher(adminMatcher, fileMatcher);

// 使用 orMatcher 进行匹配
boolean isMatch = orMatcher.matches(request);

6. 总结

Spring 提供了多种 RequestMatcher 实现类,以满足不同的请求匹配需求。通过合理地使用这些匹配器,可以灵活地定义和实施安全策略。在实际应用中,你可能需要根据业务需求选择合适的匹配器,并结合 Spring Security 的配置来实现细粒度的访问控制。

以上就是最新版Spring Security中的路径匹配方案的详细内容,更多关于Spring Security路径匹配的资料请关注脚本之家其它相关文章!

相关文章

  • springboot 如何解决yml没有spring的小叶子标志问题

    springboot 如何解决yml没有spring的小叶子标志问题

    这篇文章主要介绍了springboot 如何解决yml没有spring的小叶子标志问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-03-03
  • 解决spring项目找不到Aspect依赖注解的问题

    解决spring项目找不到Aspect依赖注解的问题

    这篇文章主要介绍了解决spring项目找不到Aspect依赖注解的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06
  • springsecurity实现拦截器的使用示例

    springsecurity实现拦截器的使用示例

    Spring Security 可以替代拦截器,同时还可以提供更加细粒度的权限控制和身份认证,本文就来介绍一下springsecurity实现拦截器的使用示例,感兴趣的可以了解一下
    2023-10-10
  • java使用apache.poi导出word文件的示例代码

    java使用apache.poi导出word文件的示例代码

    这篇文章主要介绍了java使用apache.poi导出word文件,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-07-07
  • Java设计模式之策略模式示例详解

    Java设计模式之策略模式示例详解

    策略模式属于Java 23种设计模式中行为模式之一,该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。本文将通过示例详细讲解这一模式,需要的可以参考一下
    2022-08-08
  • Javabean转换成json字符并首字母大写代码实例

    Javabean转换成json字符并首字母大写代码实例

    这篇文章主要介绍了javabean转成json字符并首字母大写代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-02-02
  • Java基于余弦方法实现的计算相似度算法示例

    Java基于余弦方法实现的计算相似度算法示例

    这篇文章主要介绍了Java基于余弦方法实现的计算相似度算法,简单说明了余弦相似性的概念、原理并结合实例形式分析了java实现余弦相似性算法的相关操作技巧,需要的朋友可以参考下
    2017-08-08
  • 使用Netty进行编解码的操作过程详解

    使用Netty进行编解码的操作过程详解

    这篇文章主要介绍了使用Netty进行编解码的操作过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-07-07
  • Java多线程并发编程 Volatile关键字

    Java多线程并发编程 Volatile关键字

    volatile 关键字是一个神秘的关键字,也许在 J2EE 上的 JAVA 程序员会了解多一点,但在 Android 上的 JAVA 程序员大多不了解这个关键字。只要稍了解不当就好容易导致一些并发上的错误发生,例如好多人把 volatile 理解成变量的锁
    2017-05-05
  • Debian 7 和 Debian 8 用户安装 Java 8的方法

    Debian 7 和 Debian 8 用户安装 Java 8的方法

    Oracle Java 8 稳定版本近期已发布,有很多新的特征变化。其中,有功能的程序支持通过“Lambda项目 ”,收到了一些安全更新和界面改进上的bug修复,使得开发人员的工作更容易。
    2014-03-03

最新评论