1 回答

TA貢獻(xiàn)1773條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以像這樣指定一個(gè)接口:
public interface HttpSecurityConfig {
Consumer<ServerHttpSecurity> configuration();
}
然后創(chuàng)建一個(gè)類,為每個(gè)端點(diǎn)實(shí)現(xiàn)它,您可以將其作為 bean 注入:
@Component
public class ServiceASecurityConfig implements HttpSecurityConfig {
@Override
public Consumer<ServerHttpSecurity> configuration() {
return (http) -> {
http.authorizeExchange()
.pathMatchers(HttpMethod.GET, "/api/serviceA/**")
.hasAuthority("PROP_A");
};
}
}
@Component
public class ServiceBSecurityConfig implements HttpSecurityConfig {
@Override
public Consumer<ServerHttpSecurity> configuration() {
return (http) -> {
http.authorizeExchange()
.pathMatchers(HttpMethod.GET, "/api/serviceB/**")
.hasAuthority("PROP_B");
};
}
}
最后修改你的SecurityWebFilterChain所以它注入所有類型的beanHttpSecurityConfig并應(yīng)用配置,就像這樣:
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http, final List<HttpSecurityConfig> httpConfigurations) {
http.securityMatcher(ServerWebExchangeMatchers.pathMatchers("/api/**"))
.authenticationManager(this.authenticationManager);
// This line replaces the individual configurations in your original question
httpConfigurations.forEach(config -> config.configuration().accept(http));
http.authorizeExchange().pathMatchers(HttpMethod.POST, "/api/login", "/api/logout", "/api/forgotPassword", "/api/confirmForgotPassword").permitAll();
http.csrf()
.disable()
.formLogin()
.authenticationEntryPoint(new HttpStatusServerEntryPoint(HttpStatus.UNAUTHORIZED))
.requiresAuthenticationMatcher(
ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, "/api/login"))
.authenticationFailureHandler(CustomSpringSecurity::onAuthenticationFailure)
.authenticationSuccessHandler(CustomSpringSecurity::onAuthenticationSuccess)
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(new CustomLogoutSuccessHandler(HttpStatus.OK));
final SecurityWebFilterChain build = http.build();
build
.getWebFilters()
.collectList()
.subscribe(
webFilters -> {
for (WebFilter filter : webFilters) {
if (filter instanceof AuthenticationWebFilter) {
AuthenticationWebFilter awf = (AuthenticationWebFilter) filter;
awf.setServerAuthenticationConverter(CustomSpringSecurity::convert);
}
}
});
return build;
}
添加回答
舉報(bào)