我试着把它做得更优雅些,但那会是更多的工作。所以我接受了这一点。你必须像你一样构建你的SecurityWebFiler链。但在你创造它之后,你必须找到这个
AuthenticationWebFilter
它是一个web过滤器,负责创建
authentication
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http.authorizeExchange()
.anyExchange().authenticated()
.and()
.formLogin()
;
final SecurityWebFilterChain build = http.build();
build.getWebFilters().collectList().subscribe(
webFilters -> {
for (WebFilter filter : webFilters){
if(filter instanceof AuthenticationWebFilter){
AuthenticationWebFilter awf = (AuthenticationWebFilter) filter;
awf.setAuthenticationConverter(new CustomHttpBasicAuthenticationConverter());
}
}
}
);
return build;
}
示例
HttpBasicAuthenticationConverter
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.util.Assert;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.function.Function;
public class CustomHttpBasicAuthenticationConverter implements Function<ServerWebExchange, Mono<Authentication>> {
private String usernameParameter = "username";
private String passwordParameter = "password";
@Override
public Mono<Authentication> apply(ServerWebExchange exchange) {
return exchange.getFormData()
.map( data -> createAuthentication(data));
}
private UsernamePasswordAuthenticationToken createAuthentication(
MultiValueMap<String, String> data) {
String username = data.getFirst(this.usernameParameter);
String password = data.getFirst(this.passwordParameter);
return new UsernamePasswordAuthenticationToken(username, password);
}
public void setUsernameParameter(String usernameParameter) {
Assert.notNull(usernameParameter, "usernameParameter cannot be null");
this.usernameParameter = usernameParameter;
}
public void setPasswordParameter(String passwordParameter) {
Assert.notNull(passwordParameter, "passwordParameter cannot be null");
this.passwordParameter = passwordParameter;
}
}