【Spring Security】基于SpringBoot3.3.4版本②如何配置免鉴权Path

发布于:2024-10-09 ⋅ 阅读:(185) ⋅ 点赞:(0)

摘要

【Spring Security】基于SpringBoot3.3.4版本①整合JWT的使用教程
在这篇文章中,详细演示了使用最新版Spring Boot,完成一个微服务开发,并使用Spring Security组件完成登录认证,同时整合了JWT,使用的RSA公私钥签名、验签。

接下来继续讲解下一个业务场景:一个真实场景的微服务,难免会有一些请求Path不需要任何鉴权,比如某些仅对内的API、允许匿名访问的资源等等。那么,如何在Spring Security体系中,把这些免鉴权的Path绕过认证呢?并且可以灵活的配置呢?

接下来让我就带着你一起解决这个业务场景中的问题吧!

本地开发环境说明

开发用到的主要框架、工具版本如下

开发依赖 版本
Spring Boot 3.3.4
Spring Security 6.3.3
JDK 21
IntelliJ IDEA 2024.2.3

【Spring Security】基于SpringBoot3.3.4版本①整合JWT的使用教程 建议大家先阅读这篇文章,本文是对这篇文章的进一步扩展。

SecurityFilterChain介绍

我们在构建SecurityFilterChain的时候,可以通过authorizeHttpRequestsCustomizer.requestMatchers(HttpMethod.POST, "/login/common").permitAll()这种方式告诉Spring Security,对于/login/common这个path不需要鉴权,代码如下

    @Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
   
    Wen3SecurityProperties wen3SecurityProperties = wen3SecurityProperties();
    http.authorizeHttpRequests(authorizeHttpRequestsCustomizer -> {
   
        authorizeHttpRequestsCustomizer
                .requestMatchers(HttpMethod.POST, "/login/common").permitAll()
                .requestMatchers(HttpMethod.GET, "/login/verify").permitAll()
                .requestMatchers(new AntPathRequestMatcher("/**/test")).permitAll()
                .anyRequest().authenticated();
    });

    // token校验过滤器
    http.addFilterBefore(jwtFilter(), UsernamePasswordAuthenticationFilter.class);

    // 禁用表单提交 取消默认的登录页面
    http.formLogin(AbstractHttpConfigurer::disable);
    // 禁用注销 取消默认的登出页面
    http.logout(AbstractHttpConfigurer::disable)

网站公告

今日签到

点亮在社区的每一天
去签到