響應式 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.