響應式 X.509 認證
類似於 Servlet X.509 認證,響應式 X.509 認證過濾器允許從客戶端提供的證書中提取認證令牌。
以下示例展示了響應式 X.509 安全配置
-
Java
-
Kotlin
@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)
}
}
}
在上述配置中,如果既未提供 principalExtractor
也未提供 authenticationManager
,則會使用預設值。預設的主體提取器是 SubjectDnX509PrincipalExtractor
,它從客戶端提供的證書中提取 CN(通用名稱)欄位。預設的認證管理器是 ReactivePreAuthenticatedAuthenticationManager
,它執行使用者賬戶驗證,檢查由 principalExtractor
提取名稱的使用者賬戶是否存在,並且未被鎖定、停用或過期。
以下示例演示瞭如何覆蓋這些預設值
-
Java
-
Kotlin
@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 中提取的,並且根本不執行使用 ReactiveUserDetailsService
的賬戶查詢。相反,如果提供的證書頒發給了名為“Trusted Org Unit”的 OU,則請求會被認證。
有關配置 Netty 和 WebClient
或 curl
命令列工具以使用雙向 TLS 並啟用 X.509 認證的示例,請參閱 github.com/spring-projects/spring-security-samples/tree/main/servlet/java-configuration/authentication/x509。