Spring Boot OAuth2Login集成Swagger-ui时的CORS跨域问题
解决Swagger UI调用OAuth2登录接口的CORS问题
原因分析
Swagger UI运行在前端域名(如localhost:8080/swagger-ui.html),调用后端接口属于跨域请求。当后端返回302重定向到Google认证页面时,浏览器的CORS策略会拦截该操作——第三方域名(accounts.google.com)未配置允许你的前端域名的CORS头,同时后端也未正确处理跨域场景下的OAuth2跳转逻辑。
解决方案
1. 配置Spring Security允许Swagger相关域名的CORS
在Spring Security配置类中添加CORS规则,允许Swagger UI的来源、请求方法及凭证携带:
@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .cors(cors -> cors.configurationSource(corsConfigurationSource())) .oauth2Login(withDefaults()) .authorizeHttpRequests(auth -> auth .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll() .anyRequest().authenticated() ); return http.build(); } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); // 替换为Swagger UI实际运行的域名 configuration.setAllowedOrigins(List.of("http://localhost:8080")); configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); configuration.setAllowedHeaders(List.of("*")); // 允许携带会话凭证(OAuth2登录依赖Cookie) configuration.setAllowCredentials(true); configuration.setExposedHeaders(List.of("Location")); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } }
2. 调整Swagger UI配置,允许携带凭证
在Swagger配置类中开启withCredentials,确保请求携带Cookie以维持会话:
@Configuration public class SwaggerConfig { @Bean public OpenAPI customOpenAPI() { return new OpenAPI() .info(new Info().title("API文档").version("v1")); } @Bean public UiConfiguration uiConfiguration() { return UiConfigurationBuilder.builder() .withCredentials(true) .build(); } }
3. 替代方案:让Swagger UI直接集成OAuth2授权流程
若上述方法仍有问题,可配置Swagger UI直接完成Google认证,再携带令牌调用接口,绕过跨域重定向限制:
@Configuration public class SwaggerConfig { @Bean public OpenAPI customOpenAPI() { OAuthFlow oAuthFlow = new OAuthFlow() .authorizationUrl("http://localhost:8080/oauth2/authorization/google") .tokenUrl("http://localhost:8080/login/oauth2/code/google") .scopes(new Scopes().addString("openid", "OpenID Connect scope")); SecurityScheme securityScheme = new SecurityScheme() .type(SecurityScheme.Type.OAUTH2) .flows(new OAuthFlows().authorizationCode(oAuthFlow)); return new OpenAPI() .info(new Info().title("API文档").version("v1")) .components(new Components().addSecuritySchemes("google-oauth2", securityScheme)) .addSecurityItem(new SecurityRequirement().addList("google-oauth2")); } }
配置完成后,Swagger UI会显示「Authorize」按钮,点击后直接跳转Google认证,完成后自动携带令牌调用接口。
4. 注意事项
- 不要同时使用通配符
*作为allowedOrigins并开启allowCredentials,浏览器会拒绝这种配置。 - 生产环境需将
allowedOrigins替换为实际的前端域名。 - 若使用Spring Boot 3.x,需使用Springdoc OpenAPI替代Springfox,核心配置逻辑一致。
内容的提问来源于stack exchange,提问作者ElieA
相关产品推荐
相关产品推荐

