响应式 X.509 认证

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

以下示例显示了一个响应式 X.509 安全配置

  • Java

  • Kotlin

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

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

以下示例演示了如何覆盖这些默认值

  • Java

  • Kotlin

@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();
}
@Bean
fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
    val extractor = SubjectX500PrincipalExtractor()
    extractor.setExtractPrincipalNameFromEmail(true)

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

    val users: ReactiveUserDetailsService = MapReactiveUserDetailsService(user)
    val authentication: ReactiveAuthenticationManager = ReactivePreAuthenticatedAuthenticationManager(users)

    return http {
        x509 {
            principalExtractor = extractor
            authenticationManager = authentication
        }
        authorizeExchange {
            authorize(anyExchange, authenticated)
        }
    }
}

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

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

© . This site is unofficial and not affiliated with VMware.