使用Spring Security保护Spring云网关

wdebmtf2  于 2022-12-12  发布在  Spring
关注(0)|答案(1)|浏览(167)

我正在为我的Spring Cloud Gateway服务配置安全性。现在我在api-gateway中只配置了一个到用户服务/api/v1/users的路由。请求被正确地路由到用户服务,直到我将Spring Security添加到依赖关系中。
即使有这样简单的配置,应该允许所有流量,我仍然得到401 Unnathorized响应:

@Configuration
@EnableWebFluxSecurity
class SecurityConfiguration {

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity serverHttpSecurity) {
        return serverHttpSecurity
                .authorizeExchange()
                .anyExchange().permitAll().and()
                .csrf().disable()
                .build();
    }
}

我做错了什么?

kgsdhlau

kgsdhlau1#

您需要创建用户来完成此操作。请参见下面所附的示例。我正在使用内存中的用户进行身份验证。注意,内存中的用户仅用于测试目的。

@Configuration
public class InMemoryUserSecurityAdapter {

@Bean
public SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
    return http
            .authorizeExchange()
            .pathMatchers("/school-library-service/**").authenticated()
            .and().authenticationManager(reactiveAuthenticationManager())
            .authorizeExchange().anyExchange().permitAll().and()
            .httpBasic().and()
            .build();
}

@Bean
ReactiveAuthenticationManager reactiveAuthenticationManager(){
    return new UserDetailsRepositoryReactiveAuthenticationManager(getInMemoryUserDetails());
}

@Bean
public MapReactiveUserDetailsService getInMemoryUserDetails() {
    UserDetails admin = User.withDefaultPasswordEncoder().username("admin1").password("password")
            .roles("ADMIN")
            .build();
    return new MapReactiveUserDetailsService(admin);
}

}
https://github.com/DeepuGeorgeJacob/school-management/blob/main/security/in-memory-user-security/src/main/java/com/school/management/config/InMemoryUserSecurityAdapter.java
快乐编码:)

相关问题