跳到主要内容
版本:7.0.2

响应式 X.509 认证

DeepSeek V3 中英对照 X.509 Authentication Reactive X.509 Authentication

类似于 Servlet X.509 认证,响应式 x509 认证过滤器允许从客户端提供的证书中提取认证令牌。

以下示例展示了响应式 x509 安全配置:

@Bean
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
http
.x509(Customizer.withDefaults())
.authorizeExchange((authorize) -> authorize
.anyExchange().authenticated()
);
return http.build();
}

在上述配置中,当未提供 principalExtractorauthenticationManager 时,将使用默认值。默认的主体提取器是 SubjectX500PrincipalExtractor,它从客户端提供的证书中提取 CN(通用名称)字段。默认的身份验证管理器是 ReactivePreAuthenticatedAuthenticationManager,它执行用户账户验证,检查由 principalExtractor 提取名称的用户账户是否存在,以及该账户是否未被锁定、禁用或过期。

以下示例展示了如何覆盖这些默认设置:

@Bean
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
SubjectX500PrincipalExtractor principalExtractor = new SubjectX500PrincipalExtractor();
principalExtractor.setExtractPrincipalNameFromEmail(true);

UserDetails user = User
.withUsername("luke@monkeymachine")
.password("password")
.roles("USER")
.build();

ReactiveUserDetailsService users = new MapReactiveUserDetailsService(user);
ReactiveAuthenticationManager authenticationManager = new ReactivePreAuthenticatedAuthenticationManager(users);

http
.x509((x509) -> x509
.principalExtractor(principalExtractor)
.authenticationManager(authenticationManager)
)
.authorizeExchange((authorize) -> authorize
.anyExchange().authenticated()
);
return http.build();
}

在前面的示例中,用户名是从客户端证书的 emailAddress 字段而非 CN 字段提取的,并且账户查找使用了自定义的 ReactiveAuthenticationManager 实例。

关于配置 Netty 和 WebClientcurl 命令行工具以使用双向 TLS 并启用 X.509 身份验证的示例,请参阅 github.com/spring-projects/spring-security-samples/tree/main/servlet/java-configuration/authentication/x509