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

如何在Spring Boot响应式应用中为指定REST API配置SSL客户端认证

针对特定API启用SSL客户端证书认证的配置方案

要实现仅对/v2/getData2接口启用SSL客户端证书认证,需完成服务器SSL配置和Spring Security规则配置两部分工作,以下是完整实现步骤:

一、服务器SSL基础配置

首先在配置文件(如application.yml)中开启HTTPS,指定服务器证书、信任的CA证书,并强制要求客户端提供证书:

server:
  port: 8443
  ssl:
    # 服务器自身证书与私钥配置
    key-store-type: PEM
    key-store: classpath:CrtCertificate.pem
    key-store-password: 你的私钥密码(若有)
    key-password: 你的私钥密码(若有)
    # 信任CA证书配置,用于验证客户端证书合法性
    trust-store-type: PEM
    trust-store: classpath:certificate.pem
    trust-store-password: CA证书密码(若有)
    # 强制要求客户端请求携带证书
    client-auth: required

二、Spring Security规则优化

你的现有配置已指定/v2/getData2需要认证,但需补充X.509认证的验证逻辑,确保只有信任CA签发的客户端证书能通过校验:

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.server.SecurityWebFilterChain;

@EnableWebFluxSecurity
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain securityFilterChain(ServerHttpSecurity http) throws Exception {
        return http
                .csrf().disable()
                .authorizeExchange(exchanges -> exchanges
                        .pathMatchers("/v2/getData2").authenticated()
                        .anyExchange().permitAll()
                )
                .x509(x509 -> x509
                        // 从客户端证书中提取用户标识,示例取证书CN字段
                        .principalExtractor(principal -> principal.getName())
                        // 可选:配置用户详情服务用于权限控制(无需权限可省略)
                        .userDetailsService(userDetailsService())
                )
                .httpBasic().disable()
                .formLogin().disable()
                .build();
    }

    // 示例用户详情服务,可根据实际需求调整
    private MapReactiveUserDetailsService userDetailsService() {
        UserDetails authorizedUser = User.withUsername("客户端证书CN字段值")
                .password("{noop}无需密码")
                .roles("API_ACCESS")
                .build();
        return new MapReactiveUserDetailsService(authorizedUser);
    }
}

关键说明

  • client-auth: required 确保所有HTTPS请求都需携带客户端证书,但通过Spring Security规则,仅/v2/getData2会校验认证状态,其他接口直接放行。
  • principalExtractor 用于从客户端证书提取用户标识,通常使用证书的CN(通用名称)字段。
  • 若不需要细粒度权限控制,可直接省略userDetailsService,仅依靠CA证书完成合法性验证即可。

内容的提问来源于stack exchange,提问作者18-5112- J. YAZHILAN

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 05:22:14