Spring安全配置:基本身份验证+Spring云网关



我有一个Reactive Spring Boot应用程序,它负责使用Spring Cloud Gateway(即它是API网关(将请求路由到下游服务。该应用程序有一些需要保护的执行器端点,因此我只想使用一个简单的安全性,比如基本身份验证。

我想配置该应用程序,要求使用基本身份验证(使用配置的Spring安全用户和密码(对/actuator/refresh的请求进行授权。所有到其他端点的请求,,即使它们包括基本身份验证,也只需要传递到下游服务。

我当前的Spring安全配置:

@Bean
@Order(1)
SecurityWebFilterChain securityWebFilterChain(final ServerHttpSecurity http) {
http.authorizeExchange(exchanges -> {
exchanges.matchers(EndpointRequest.toAnyEndpoint().excluding(HealthEndpoint.class, InfoEndpoint.class)).hasRole("ACTUATOR"); // requires Http Basic Auth
});
http.httpBasic(withDefaults()); // if not enabled, you cannot get the ACTUATOR role
return http.build();
}
@Bean
@Order(2)
SecurityWebFilterChain permitAllWebFilterChain(final ServerHttpSecurity http) {
http.authorizeExchange(exchanges -> exchanges.anyExchange().permitAll()); // allow unauthenticated access to any endpoint (other than secured actuator endpoints?)
http.httpBasic(ServerHttpSecurity.HttpBasicSpec::disable); // disable Http Basic Auth for all other endpoints
return http.build();
}

API网关不传播用于下游服务的请求。在该设置中,弹簧引导服务返回401,而预期/需要200。

有什么想法吗?为什么这个配置不起作用?否则应该如何配置?

我不确定是什么坏了,但你试过把它们组合在一起,只使用一个过滤器吗?

@EnableWebFluxSecurity
public class MyExplicitSecurityConfiguration {
@Bean
public MapReactiveUserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("user")
.roles("ACTUATOR")
.build();
return new MapReactiveUserDetailsService(user);
}
@Bean
SecurityWebFilterChain securityWebFilterChain(final ServerHttpSecurity http) {
http.authorizeExchange(exchanges -> {
exchanges.matchers(EndpointRequest.toAnyEndpoint()
.excluding(HealthEndpoint.class, InfoEndpoint.class))
.hasRole("ACTUATOR");
exchanges.anyExchange().permitAll();
}).httpBasic(withDefaults());
return http.build();
}
}

另一个好办法是启用调试日志记录并查看失败的部分。

这是通过在application.properties中定义来实现的

logging.level.org.springframework.security=DEBUG

最新更新