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

Spring Boot 3.2资源服务器Swagger UI授权失败问题求助

Spring Boot Security 3.2 资源服务器Swagger v3 401未授权问题排查与解决

先梳理核心问题点,再给出可落地的修正方案:

1. 端点匹配不全或规则错误

Swagger v3的完整资源端点不止常规配置的几个,漏配会导致UI依赖的静态资源(CSS、JS等)被拦截,最终引发UI无法加载。需要放行的完整端点集合包括:

  • /swagger-ui/**
  • /v3/api-docs/**
  • /swagger-ui.html
  • /swagger-resources/**
  • /webjars/swagger-ui/**

2. 安全规则顺序错误

Spring Security的过滤器链按配置顺序匹配,放行规则必须放在认证规则之前,否则先触发anyRequest().authenticated()会拦截所有请求,包括Swagger端点。

3. 依赖兼容性问题

确保SpringDoc Swagger依赖与Spring Boot 3.2兼容,推荐使用springdoc-openapi-starter-webmvc-ui的2.2.0及以上版本:

<!-- Maven依赖示例 -->
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.2.0</version>
</dependency>

修正后的配置示例

YAML配置(application.yml)

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://localhost:8080/auth-service # 替换为你的认证服务器实际地址

资源服务器Java配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class ResourceServerConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                // 优先放行所有Swagger相关端点
                .requestMatchers(
                    "/swagger-ui/**",
                    "/v3/api-docs/**",
                    "/swagger-ui.html",
                    "/swagger-resources/**",
                    "/webjars/swagger-ui/**"
                ).permitAll()
                // 其余端点需认证
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> jwt
                    .issuerUri("http://localhost:8080/auth-service")
                )
            );
        return http.build();
    }
}

额外排查点

  • 若存在自定义过滤器,需确保过滤器也放过Swagger端点;
  • 测试前清除浏览器缓存或使用隐身窗口,避免旧的无效JWT令牌干扰;
  • 可先单独访问/v3/api-docs端点,若能返回JSON数据,说明放行规则已生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 06:23:17