通过WebFlux的证书进行身份验证? [英] Authentication by certificate for WebFlux?
问题描述
在用于Spring Boot Web的常规Servlet API中,存在HttpSecurity
配置的.x509()
.但是在WebFlux的ServerHttpSecurity
中,我找不到任何类似的东西.
In the regular Servlet API for Spring Boot Web, there is the .x509()
of the HttpSecurity
configuration. But in WebFlux's ServerHttpSecurity
I can't find anything similar to it.
WebFlux中的.x509().subjectPrincipalRegex(...)
等同于什么
What is the equivalent of.x509().subjectPrincipalRegex(...)
in WebFlux
最终目标是获得证书主题作为发送给ReactiveUserDetailsService
的用户名.
End goal is to get the certificate subject as the username sent to ReactiveUserDetailsService
.
推荐答案
我不认为在Spring的早期版本中有X509过滤器,因此您必须实现自己的版本.幸运的是,方便的org.springframework.security.web.server.authentication.AuthenticationWebFilter
提供了身份验证流程的模式,但是您必须自己从证书/请求中提取主题.
I don't think there is a X509 filter as there was in the previous versions of spring, so you'll have to implement your own version of it. Fortunately the handy org.springframework.security.web.server.authentication.AuthenticationWebFilter
provides the pattern for the authentication flow but you'll have to extract the subject from the cert/request yourself.
您要做的第一件事是设置身份验证转换器,以从证书中提取主题.
The first thing you'll have to do is setup an the authentication converter to extract the subject from the cert.
public class X509AuthenticationConverter implements Function<ServerWebExchange, Mono<Authentication>> {
@Override
public Mono<Authentication> apply(ServerWebExchange exchange) {
ServerHttpRequest request = exchange.getRequest();
try {
// extract credentials here
Authentication authentication = ...
return Mono.just(authentication);
} catch (Exception e) {
// log error here
return Mono.empty();
}
}
}
现在,在我们的配置中,我们创建过滤器和转换器bean,并将转换器设置为过滤器.
Now on our config we create the filter and converter beans and set the converter into the filter.
@Bean
public X509AuthenticationConverter x509AuthenticationConverter() {
return new X509AuthenticationConverter();
}
@Bean
public AuthenticationWebFilter x509AuthenticationWebFilter(ReactiveAuthenticationManager reactiveAuthenticationManager,
X509AuthenticationConverter x509AuthenticationConverter) {
AuthenticationWebFilter authenticationWebFilter = new AuthenticationWebFilter(reactiveAuthenticationManager);
authenticationWebFilter.setAuthenticationConverter(x509AuthenticationConverter);
return authenticationWebFilter;
}
最后配置安全性
@Bean
SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http, AuthenticationWebFilter x509AuthenticationWebFilter) {
return http
.addFilterAt(x509AuthenticationWebFilter, SecurityWebFiltersOrder.AUTHENTICATION)
//...
.build();
}
这与其他身份验证机制同样有效.
This will work just as well with other authentication mechanisms.
这篇关于通过WebFlux的证书进行身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!