首页  >  文章  >  Java  >  Spring Security 6 中的新 requestMatchers

Spring Security 6 中的新 requestMatchers

WBOY
WBOY原创
2024-07-19 12:18:31706浏览

New requestMatchers in Spring Security 6

在 Spring Security 6 中,requestMatchers 方法已替换了已弃用的 antMatchers、mvcMatchers 和 regexMatchers 方法,用于配置基于路径的访问控制。以下是关于新 requestMatchers 的要点:

在authorizeHttpRequests中使用requestMatchers

HttpSecurity配置中的authorizeHttpRequests方法允许您配置细粒度的请求匹配以进行访问控制。您可以使用 requestMatchers 方法来指定应允许或验证哪些请求。例如:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    return http.authorizeHttpRequests(auth -> auth
        .requestMatchers("/greet").permitAll()
        .anyRequest().authenticated())
        .formLogin()
        .build();
}

此配置允许无需身份验证即可访问 /greet 端点,同时需要对所有其他请求进行身份验证。

requestMatchers 与 securityMatchers

有两个类似的方法:requestMatchers 和 securityMatchers。两者都根据类路径中 Spring MVC 的存在情况选择最合适的 RequestMatcher 实现:

  • 如果 Spring MVC 存在,它使用 MvcRequestMatcher
  • 如果 Spring MVC 不存在,则回退到 AntPathRequestMatcher

主要区别是securityMatchers用在WebSecurityCustomizer等地方,而requestMatchers用在authorizeHttpRequests中。

选择正确的匹配器

requestMatchers 方法允许您根据模式或其他条件匹配请求,而无需依赖特定的匹配器(如 AntPathRequestMatcher 或 RegexRequestMatcher)。这提供了更大的灵活性和更好的默认值。

要使用特定的匹配器,您可以将 RequestMatcher 实现传递给 requestMatchers 方法:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    return http.authorizeHttpRequests(auth -> auth
        .requestMatchers(new AntPathRequestMatcher("/greet")).permitAll()
        .anyRequest().authenticated())
        .formLogin()
        .build();
}

总之,Spring Security 6 中新的 requestMatchers 方法提供了一种更灵活、更安全的方式来配置基于路径的访问控制,根据应用程序的依赖关系选择最合适的 RequestMatcher 实现。

以上是Spring Security 6 中的新 requestMatchers的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn