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

Spring Boot 3+Spring Security+JWT环境下Swagger UI无法访问(403错误)

Spring Boot 3集成Swagger UI返回403错误的解决方案

问题分析

你遇到的403错误主要由以下几个原因导致:

  1. Swagger相关路径未完全加入Spring Security白名单:springdoc-openapi 2.x版本的Swagger UI除了/swagger-ui/**,还需要放行/swagger-ui.html入口路径;
  2. 依赖版本不兼容:你使用的springdoc-openapi-starter-webmvc-ui 2.1.0与Spring Boot 3.1.1存在适配问题;
  3. JWT过滤器拦截了白名单路径:自定义的JWT过滤器可能未跳过Swagger相关请求。

具体修复步骤

1. 升级springdoc依赖版本

将springdoc依赖升级到与Spring Boot 3.1.1兼容的版本(推荐2.2.0及以上):

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.2.0</version>
</dependency>

2. 完善Security白名单配置

补充/swagger-ui.html到白名单,确保所有Swagger相关路径都被放行:

private static final String[] AUTH_WHITE_LIST = {
        "/v3/api-docs/**",
        "/swagger-ui/**",
        "/swagger-ui.html", // 新增该路径
        "/v2/api-docs/**",
        "/swagger-resources/**"
};

如果字符串匹配仍有问题,可显式使用AntPathRequestMatcher确保路径匹配规则生效:

public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests((requests) -> requests
                    // 显式指定匹配器放行Swagger路径
                    .requestMatchers(AntPathRequestMatcher.antMatcher("/v3/api-docs/**")).permitAll()
                    .requestMatchers(AntPathRequestMatcher.antMatcher("/swagger-ui/**")).permitAll()
                    .requestMatchers(AntPathRequestMatcher.antMatcher("/swagger-ui.html")).permitAll()
                    .requestMatchers("/auth/**").permitAll()
                    .requestMatchers("/users/createUser").permitAll()//todo fix in the future
                    .requestMatchers("/users/getProfile").permitAll()//todo fix in the future
                    .requestMatchers("/users/**").hasRole("ADMIN")
                    .requestMatchers("/contacts/**").hasRole("ADMIN")
                    .anyRequest().authenticated()
            );

    http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);

    return http.build();
}

3. 确保JWT过滤器不拦截白名单路径

在JwtRequestFilter的doFilterInternal方法中,先判断请求路径是否在白名单内,若是则直接放行:

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    String requestUri = request.getRequestURI();
    AntPathMatcher pathMatcher = new AntPathMatcher();
    
    // 检查是否为白名单路径,是则直接放行
    for (String whitePath : AUTH_WHITE_LIST) {
        if (pathMatcher.match(whitePath, requestUri)) {
            filterChain.doFilter(request, response);
            return;
        }
    }
    
    // 原有JWT验证逻辑
    // ...
}

验证

完成上述修改后,重启项目,访问http://localhost:端口号/swagger-ui.html即可正常打开Swagger UI界面。

内容的提问来源于stack exchange,提问作者Itzik.B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 15:14:56