对于最新的稳定版本,请使用 Spring Security 6.3.1Spring中文文档

对于最新的稳定版本,请使用 Spring Security 6.3.1Spring中文文档

Servlet X.509 身份验证类似,反应式 x509 身份验证过滤器允许从客户端提供的证书中提取身份验证令牌。Spring中文文档

下面是反应式 x509 安全配置的示例:Spring中文文档

@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
	http
		.x509(withDefaults())
		.authorizeExchange(exchanges -> exchanges
		    .anyExchange().permitAll()
		);
	return http.build();
}
@Bean
fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
    return http {
        x509 { }
        authorizeExchange {
            authorize(anyExchange, authenticated)
        }
    }
}

在上面的配置中,当既不提供也不提供时,将使用默认值。默认主体提取器是从客户端提供的证书中提取 CN(公用名)字段。默认身份验证管理器用于执行用户帐户验证,检查用户帐户是否具有 exists 提取的名称,并且该帐户未被锁定、禁用或过期。principalExtractorauthenticationManagerSubjectDnX509PrincipalExtractorReactivePreAuthenticatedAuthenticationManagerprincipalExtractorSpring中文文档

下一个示例演示如何重写这些默认值。Spring中文文档

@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
	SubjectDnX509PrincipalExtractor principalExtractor =
	        new SubjectDnX509PrincipalExtractor();

	principalExtractor.setSubjectDnRegex("OU=(.*?)(?:,|$)");

	ReactiveAuthenticationManager authenticationManager = authentication -> {
		authentication.setAuthenticated("Trusted Org Unit".equals(authentication.getName()));
		return Mono.just(authentication);
	};

	http
		.x509(x509 -> x509
		    .principalExtractor(principalExtractor)
		    .authenticationManager(authenticationManager)
		)
		.authorizeExchange(exchanges -> exchanges
		    .anyExchange().authenticated()
		);
	return http.build();
}
@Bean
fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain? {
    val customPrincipalExtractor = SubjectDnX509PrincipalExtractor()
    customPrincipalExtractor.setSubjectDnRegex("OU=(.*?)(?:,|$)")
    val customAuthenticationManager = ReactiveAuthenticationManager { authentication: Authentication ->
        authentication.isAuthenticated = "Trusted Org Unit" == authentication.name
        Mono.just(authentication)
    }
    return http {
        x509 {
            principalExtractor = customPrincipalExtractor
            authenticationManager = customAuthenticationManager
        }
        authorizeExchange {
            authorize(anyExchange, authenticated)
        }
    }
}

在此示例中,从客户端证书的 OU 字段而不是 CN 中提取用户名,并且根本不执行帐户查找。相反,如果提供的证书颁发给名为“受信任的组织单位”的 OU,则将对请求进行身份验证。ReactiveUserDetailsServiceSpring中文文档

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