Spring Boot Security:如何禁用Swagger UI的安全校验
要让你的Swagger UI无需OAuth2验证即可访问,同时保留REST端点的安全保护,需要分两步配置:Spring Security放行Swagger路径,以及调整Swagger的API文档配置。
1. 配置Spring Security放行Swagger相关路径
首先要确保Spring Security不会拦截Swagger UI和API文档的静态资源路径。根据你使用的Spring Security版本,选择对应的配置方式:
方式一:使用WebSecurityConfigurerAdapter(旧版Spring Security)
如果你的项目还在用WebSecurityConfigurerAdapter,重写configure(WebSecurity web)方法添加忽略路径:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override public void configure(WebSecurity web) throws Exception { // 放行Swagger相关的所有路径 web.ignoring() .antMatchers( "/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**", "/swagger-resources" ); } // 其他安全配置(比如资源服务器配置) @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and() .oauth2ResourceServer().jwt(); // 可根据你的OAuth2实际配置调整 } }
方式二:使用SecurityFilterChain(Spring Security 5.7+ 推荐方式)
如果是新版本的Spring Security,用SecurityFilterChain来配置放行规则:
@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(auth -> auth // 允许所有人访问Swagger相关路径 .requestMatchers( "/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**" ).permitAll() // 其他所有端点需要认证 .anyRequest().authenticated() ) // 你的OAuth2资源服务器配置,比如JWT或者令牌验证逻辑 .oauth2ResourceServer(oauth2 -> oauth2.jwt()); return http.build(); } }
2. 调整Swagger配置(可选但推荐)
虽然上面的配置已经能让你直接访问Swagger UI,但如果想在Swagger UI里方便测试受保护的接口,可以配置Swagger支持OAuth2的client_credentials模式,省去手动构造令牌请求的麻烦:
@Configuration @OpenAPIDefinition(info = @Info(title = "你的API文档", version = "v1", description = "REST接口文档")) public class SwaggerConfig { @Bean public OpenAPI customOpenAPI() { // 定义OAuth2的client_credentials流配置 OAuthFlow clientCredentialsFlow = new OAuthFlow() .tokenUrl("http://localhost:8080/oauth/token") // 替换成你的授权服务器令牌地址 .scopes(new Scopes() .addString("xxx", "第一个权限描述") // 替换成你实际的scope .addString("xxx", "第二个权限描述")); // 配置安全方案 SecurityScheme oauth2Scheme = new SecurityScheme() .type(SecurityScheme.Type.OAUTH2) .flows(new OAuthFlows().clientCredentials(clientCredentialsFlow)); return new OpenAPI() .components(new Components().addSecuritySchemes("oauth2", oauth2Scheme)) // 如果不想让所有接口默认要求授权,直接注释掉下面这行即可 // .addSecurityItem(new SecurityRequirement().addList("oauth2")); } }
要是你完全不想在Swagger UI里显示任何安全提示,注释掉addSecurityItem这行就行——打开Swagger UI后可以直接查看接口,测试时手动在请求头里添加Authorization: Bearer <你的令牌>即可。
验证配置
启动应用后,访问http://localhost:8080/swagger-ui/index.html(替换成你的应用实际端口),应该能直接打开Swagger UI,无需任何登录验证,同时你的REST端点依然会要求OAuth2令牌才能访问。
内容的提问来源于stack exchange,提问作者starman1979

