You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot集成JJWT后Swagger/OpenAPI端点返回403问题求助

解决SpringBoot集成JJWT后Swagger/OpenAPI端点403问题

问题核心

SpringBoot Maven项目集成JJWT 0.12.3后,使用springdoc-openapi 2.3.0生成的Swagger相关端点(如/auto-pass/v3/api-docs)返回403状态码,即使配置了放行规则也无效;同时存在Mustache模板路径警告,SwaggerUI始终无法访问。

解决方案

1. 修正Spring Security放行规则

核心错误:Spring Security的requestMatchers匹配的是上下文路径之外的Servlet路径,不需要在规则中添加项目上下文路径/auto-pass,否则会导致路径匹配失败。

修正后的安全配置代码:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
            .csrf(AbstractHttpConfigurer::disable)
            .cors(AbstractHttpConfigurer::disable)
            .sessionManagement(session -> session
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(authorize -> authorize
                    .requestMatchers(HttpMethod.POST, "/api/signup", "/api/login").permitAll()
                    // 仅匹配上下文后的相对路径,适配springdoc-openapi 2.x端点
                    .requestMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html", "/webjars/**").permitAll()
                    .anyRequest().authenticated()
            )
            .authenticationProvider(authenticationProvider())
            .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    return http.build();
}

2. 补充springdoc-openapi基础配置(可选)

虽然官方称配置可选,但添加简单配置可确保文档生成稳定,同时明确端点路径:

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenApiConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("Auto-Pass API")
                        .version("1.0")
                        .description("API文档:Auto-Pass项目"));
    }
}

在application.yml中添加springdoc路径配置:

springdoc:
  api-docs:
    path: /v3/api-docs
  swagger-ui:
    path: /swagger-ui.html

3. 消除Mustache警告

该警告与SwaggerUI无关,是OpenAPI代码生成插件默认依赖Mustache模板但项目无模板文件导致。可在application.properties中关闭检查:

spring.mustache.check-template-location=false

4. 验证端点访问

修正后访问以下地址:

  • API文档JSON:http://localhost:9090/auto-pass/v3/api-docs
  • SwaggerUI页面:http://localhost:9090/auto-pass/swagger-ui.html

关键注意事项

  • springdoc-openapi 2.x版本已弃用旧版Swagger的/swagger-resources/**路径,需使用/swagger-ui/**替代。
  • 所有Spring Security路径规则均无需包含项目上下文路径,框架会自动处理上下文路径与Servlet路径的拼接。

内容的提问来源于stack exchange,提问作者Raphe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 05:23:15