drapo
drapo

Reputation: 35

Securing Spring Cloud Gateway with Spring Security

I am struggling with configuring security for my Spring Cloud Gateway service. For now i have configured in my api-gateway just one route to user service /api/v1/users. Requests are correctly routed to user service untill I add Spring Security to the dependescies.

Even with that simple config, that should allow all traffic, I am still getting 401 Unathorized response:

@Configuration
@EnableWebFluxSecurity
class SecurityConfiguration {

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

What am I doing wrong?

Upvotes: 2

Views: 6613

Answers (1)

Deepu George Jacob
Deepu George Jacob

Reputation: 474

You need to create user to do that. See the sample attached in below. I am using in-memory user to authenticate. Note in-memory user is just for testing purpose only.


    @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

Happy coding :)

Upvotes: 2

Related Questions