Search code examples
spring-bootkeycloakspring-cloudspring-cloud-gatewayspring-oauth2

Securing Spring Cloud Gateway with bearer-only


I currently want to secure my microservice architecture with a Spring Cloud Gateway. There is FrontEnd which authenticates itself to a Keycloak server and then sends the token with every request. Now it is the case that only the gateway should be exposed to the outside and the individual services will not be accessible from the outside.

How can I validate the bearer token at the keycloak server?

I have searched the internet for some time but have not found anything yet where the token has been validated. Everywhere the authentication was done via the gateway and then the token was validated by the individual services. However, when I declare the gateway as an OAuth2 resource server, the whole thing does not work.


Solution

  • I managed to get It to work.

    My security config look as follows:

    @Configuration
    @EnableWebFluxSecurity
    public class SecurityConfig {
        @Bean
        public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
            http.authorizeExchange(exchanges -> exchanges.anyExchange().authenticated())
                    .oauth2ResourceServer().jwt();
            http.csrf().disable();
            return http.build();
        }
    
    }
    

    Moreover but don't necessary I added a CorsFilter:

    @Configuration
    public class PreFlightCorsConfiguration {
    
        @Bean
        public CorsWebFilter corsFilter() {
            return new CorsWebFilter(corsConfigurationSource());
        }
    
        @Bean
        CorsConfigurationSource corsConfigurationSource() {
            final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            CorsConfiguration config = new CorsConfiguration().applyPermitDefaultValues();
            config.addAllowedMethod( HttpMethod.GET);
            config.addAllowedMethod( HttpMethod.PUT);
            config.addAllowedMethod( HttpMethod.POST);
            config.addAllowedMethod( HttpMethod.OPTIONS);
            config.addAllowedMethod(HttpMethod.DELETE);
            source.registerCorsConfiguration("/**", config);
            return source;
        }
    }
    

    And the security dependencys I use are:

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-oauth2-client</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-security</artifactId>
         <version>2.2.5.RELEASE</version>
      </dependency>