gpt4 book ai didi

java - 使用 spring SecurityWebFilterChain 如何禁用/阻止除少数已知路径之外的所有非 https 请求

转载 作者:行者123 更新时间:2023-12-04 04:02:00 26 4
gpt4 key购买 nike

我在 Spring Boot Webflux 应用程序中使用 Spring security 主要在 HTTPS 上提供流量服务。港口。但是,作为操作要求,我需要在我的 Spring Boot 应用程序中支持几个非安全的 REST API 路径以进行健康检查等,这些路径需要在 HTTP 上公开。以及。
那么,除了使用 SecurityWebFilterChain 的已知路径之外,我如何强制执行对 HTTPS 的所有请求? bean 角,扁 bean ?
这就是我如何定义我的 SecurityWebFilterChain bean 角,扁 bean :

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {
@Bean
SecurityWebFilterChain webFilterChain( ServerHttpSecurity http )
throws Exception {
return http
.authorizeExchange(exchanges -> exchanges
.anyExchange().permitAll()
.and()
.exceptionHandling()
.authenticationEntryPoint((exchange, exception) ->
Mono.error(exception))
)
.csrf().disable()
.headers().disable()
.logout().disable()
.build();
}
}
这显然不会按预期工作,因为它允许所有请求使用 HTTPHTTPS计划而 我要一直执行HTTPS除了路径,例如/health .
请建议我需要在上面的代码中进行哪些更改才能完成此操作。

最佳答案

这是我想出的解决这个问题的方法。我在 .matchers( customMatcher ) 中调用自定义匹配器方法

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

private static final Set<String> UNSECURED = new HashSet<>(
Arrays.asList ( new String[] { "/health", "/heartbeat" } ) );

@Bean
SecurityWebFilterChain webFilterChain( final ServerHttpSecurity http ) {
return http
.authorizeExchange(
exchanges -> exchanges
.matchers( this::blockUnsecured ).permitAll()
.and()
.exceptionHandling()
.authenticationEntryPoint(
(exchange, exception) -> Mono.error(exception))
)
.csrf().disable()
.headers().disable()
.logout().disable()
.httpBasic().disable()
.build();
}

Mono<MatchResult> blockUnsecured( final ServerWebExchange exchange ) {
// Deny all requests except few known ones using "http" scheme
URI uri = exchange.getRequest().getURI();

boolean invalid = "http".equalsIgnoreCase( uri.getScheme() ) &&
!UNSECURED.contains ( uri.getPath().toLowerCase() );
return invalid ? MatchResult.notMatch() : MatchResult.match();
}
}
不确定是否有更好的方法来做同样的事情。

关于java - 使用 spring SecurityWebFilterChain 如何禁用/阻止除少数已知路径之外的所有非 https 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62936018/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com