Search code examples
springauthenticationspring-securityspring-cloud-gateway

Logging a user in Spring Cloud Gateway with SecurityFilterChain


What I do ty? Hi folks, i'm trying to create a gateway (with Spring cloud gateway and Spring boot 3.0.0) that manages authentication and authorisation of routes.

What is my problem? The problem I have is that I'm using springSecurityFilterChain and I can't get anything to run before this filter, so I can't authenticate a user if he wants to acces a private route.

What do I want? I want to know how I can authenticate a user before it goes through the filterChain (I've alredy tried many things I've seen in forums, posts, etc. and I have not been able to do it :/).

My code

@Configuration
@EnableWebFluxSecurity
public class WebfluxSecurityConfig{

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http.csrf().disable()
        .authorizeExchange()
        .pathMatchers(Routes.PUBLIC_ROUTES).permitAll()    //Public routes
        .pathMatchers(Routes.AUTH_ROUTES).authenticated(); //Authenticate routes
 
        return http.build();
    }
    
}

I am trying to authenticate a user before the springSecurityFilterChain in Spring Cloud Gateway, currently I have not been able to do so as I have not been able to place any filter to authenticate before the filter chain.


Solution

  • 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.

    https://github.com/DeepuGeorgeJacob/school-management/blob/main/security/in-memory-user-security/src/main/java/com/school/management/config/InMemoryUserSecurityAdapter.java

    @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);
    }
    

    }

    To log the events try this logging.level.org.springframework.security=TRACE in your properties file

    Happy coding :)