You need to enable JavaScript to run this app. Spring Security实现差异化路径认证:SwaggerUI用账号密码,其余用JWT
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security实现差异化路径认证:SwaggerUI用账号密码,其余用JWT

解决Spring Boot中Swagger UI与API端点的双重认证配置问题

你的问题出在Swagger专用过滤器链的配置不完整——缺少HTTP Basic认证启用逻辑、密码未加密、未明确要求路径认证,导致优先级配置未生效。以下是正确的双重认证配置方案:

1. 配置Swagger专属认证过滤器链(优先级最高)

创建优先级为1的过滤器链,专门处理Swagger相关路径,采用HTTP Basic认证+内存硬编码用户:

@Bean
@Order(1)
public SecurityFilterChain swaggerSecurityFilterChain(HttpSecurity http) throws Exception {
    // 构建内存用户,密码必须加密(Spring Security强制要求)
    UserDetails admin = User.withUsername("admin")
            .password(passwordEncoder().encode("12345"))
            .roles("ADMIN")
            .build();

    http
            // 匹配所有Swagger相关路径,包括UI页面和接口文档
            .requestMatchers(matchers -> matchers
                    .antMatchers("/swagger-ui/**", "/v3/api-docs/**"))
            // 启用HTTP Basic认证模式
            .httpBasic(Customizer.withDefaults())
            // 要求Swagger路径必须经过认证
            .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
            // 禁用CSRF(Swagger UI为静态页面,无需CSRF保护)
            .csrf(csrf -> csrf.disable())
            // 保持无状态会话,与原有API配置一致
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

    return http.build();
}

2. 保留原有OAuth2认证过滤器链(优先级次之)

调整原有过滤器链优先级为2,处理非Swagger的API路径:

@Bean
@Order(2)
public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception {
    http
            // 匹配所有API相关路径
            .requestMatchers(matchers -> matchers
                    .antMatchers("/v1/**", "/webhook/stripe/**", "/forgotPassword/**", "/public/**"))
            .authorizeHttpRequests(auth -> auth
                    // 保留原有匿名路径配置
                    .antMatchers("/webhook/stripe/**", "/forgotPassword/**", "/public/**").anonymous()
                    // 其他API路径需要OAuth2认证
                    .anyRequest().authenticated())
            // 保留原有OAuth2资源服务器配置
            .oauth2ResourceServer(oauth2 -> oauth2
                    .jwt(jwt -> jwt
                            .decoder(jwtDecoder())
                            .jwtAuthenticationConverter(jwtAuthenticationConverter())))
            // 保持无状态会话
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .csrf(csrf -> csrf.disable());

    return http.build();
}

3. 添加密码加密Bean

Spring Security禁止使用明文密码,必须配置密码编码器:

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

关键配置说明

  • 优先级顺序:@Order(1)的过滤器链会优先匹配路径,一旦匹配到Swagger相关请求,就会直接用HTTP Basic认证处理,不会进入后续的OAuth2过滤器链
  • 路径覆盖:必须包含/v3/api-docs/**,否则Swagger UI无法加载接口文档
  • 认证模式启用:必须调用httpBasic(Customizer.withDefaults())才能触发用户名密码弹窗,之前的配置缺少这一核心步骤
  • 密码加密:使用BCrypt加密密码,符合Spring Security的安全规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:53:15