SpringSecurity6中的新requestMatchers
在 spring security 6 中,requestmatchers 方法取代了已弃用的 antmatchers、mvcmatchers 和 regexmatchers 方法,用于配置基于路径的访问控制。以下是关于新 requestmatchers 的要点:
在authorizehttprequests中使用requestmatchers
httpsecurity配置中的authorizehttprequests方法允许您配置细粒度的请求匹配以进行访问控制。您可以使用 requestmatchers 方法来指定应允许或验证哪些请求。例如:
@beanpublic 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 方法:
@Beanpublic 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的详细内容,更多请关注范的资源库其它相关文章!