Как обезопасить Spring Cloud Gateway с помощью Keycloak MultiTenancy? - PullRequest
0 голосов
/ 16 марта 2020

Я пытаюсь защитить свой Spring Cloud Gateway, используя Keycloak с несколькими арендаторами. Я начал с следующих руководств:

Итак Я начал с добавления зависимости адаптера и реализации пользовательского KeycloakConfigResolverm, но затем обнаружил, что адаптер все еще использует Spring-Boot-Starter-Web, MVC & Servlets, которые несовместимы со шлюзом https://github.com/spring-cloud/spring-cloud-gateway/issues/1473 .

Это мое приложение-шлюз:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class GatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}

Здесь я определяю свой пользовательский KeycloakConfigResolver с помощью заголовка Tenant.

import org.keycloak.adapters.KeycloakDeployment;
import org.keycloak.adapters.KeycloakDeploymentBuilder;
import org.keycloak.adapters.spi.HttpFacade;
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.keycloak.representations.adapters.config.AdapterConfig;

/**
 * KeycloakConfigResolver by the Tenant header of the request.
 */
public class KeycloakTenantConfigResolver extends KeycloakSpringBootConfigResolver {
    @Override
    public KeycloakDeployment resolve(HttpFacade.Request request) {
        String tenant = request.getHeader("tenant");

        AdapterConfig config = new AdapterConfig();

        config.setRealm(tenant);
        config.setBearerOnly(true);
        config.setAuthServerUrl("http://localhost:8000/auth/");
        config.setResource("GATEWAY");

        return KeycloakDeploymentBuilder.build(config);
    }
}

и соответствующего поставщика @Bean:

import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class KeycloakTenant {
    @Bean
    public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
        // Use the KeycloakConfigResolver by the Tenant header
        return new KeycloakTenantConfigResolver();
    }
}

Это моя конфигурация безопасности, выходящая из конфигурации, предоставленной Keycloak:

import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter;
import org.keycloak.adapters.springsecurity.filter.KeycloakPreAuthActionsFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.preauth.x509.X509AuthenticationFilter;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@KeycloakConfiguration
@ConditionalOnProperty(name = "keycloak.enabled", havingValue = "true", matchIfMissing = true)
public class KeycloakSecurity extends KeycloakWebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // The bean keycloakAuthenticationProvider() is pre-defined in the class KeycloakWebSecurityConfigurerAdapter
        KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
        // We use the SimpleAuthorityMapper to make sure roles are not prefixed with 'ROLE_'
        keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
        auth.authenticationProvider(keycloakAuthenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Disable CSRF because of API mode
        http.csrf().disable()
                .sessionManagement()
                // Use the defined bean
                .sessionAuthenticationStrategy(sessionAuthenticationStrategy())
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                // Keycloak filters
                .and()
                .addFilterBefore(new KeycloakPreAuthActionsFilter(), LogoutFilter.class)
                .addFilterBefore(new KeycloakAuthenticationProcessingFilter(authenticationManager()), X509AuthenticationFilter.class)
                .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint())
                // delegate logout endpoint to spring security
                .and()
                .logout()
                .addLogoutHandler(keycloakLogoutHandler())
                .logoutUrl("/logout")
                .logoutSuccessHandler(
                        // Logout handler for API
                        (HttpServletRequest request, HttpServletResponse response, Authentication authentication) ->
                                response.setStatus(HttpServletResponse.SC_OK)
                )
                .and()
                .authorizeRequests()
                // It is necessary to not secure calls via the HTTP OPTIONS method to allow
                // frameworks like Angular to retrieve information from an endpoint.
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                // Unsecured routes
                .antMatchers("/", "/logout").permitAll()
                // Administration routes
                .antMatchers("/administration/**").hasRole("ADMIN")
                // All the remaining routes are accessible only if the user is authenticated.
                .anyRequest().authenticated();
    }

    // ...............................Beans...............................
    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        // Required for bearer-only applications
        return new NullAuthenticatedSessionStrategy();
    }
}

Вот мои свойства

server:
  port: ${SERVER_PORT:8761}
spring:
  application:
    name: Registry-${random.value}
eureka:
  instance:
    appname: Registry
    hostname: ${SERVER_HOST:localhost}
  client:
    register-with-eureka: ${REGISTER:false}
    fetch-registry: ${FETCH:false}
    service-url:
      defaultZone: ${DEFAULT_ZONE:http://localhost:8761/eureka}

и это pom. xml проекта:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>app</groupId>
    <artifactId>gateway</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>gateway</name>
    <description>API Gateway</description>

    <properties>
        <java.version>13</java.version>
        <spring-cloud.version>Hoxton.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-spring-boot-starter</artifactId>
            <version>9.0.0</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Если я запускаю проект, я получаю следующую ошибку с Tomcat:

2020-03-16 18:54:48.733 ERROR 5900 --- [  restartedMain] o.s.b.web.embedded.tomcat.TomcatStarter  : Error starting Tomcat context. Exception: org.springframework.beans.factory.BeanCreationException. Message: Error creating bean with name 'servletEndpointRegistrar' defined in class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfiguration$WebMvcServletEndpointManagementContextConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.endpoint.web.ServletEndpointRegistrar]: Factory method 'servletEndpointRegistrar' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'gatewayControllerEndpoint' defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration$GatewayActuatorConfiguration.class]: Unsatisfied dependency expressed through method 'gatewayControllerEndpoint' parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'modifyResponseBodyGatewayFilterFactory' defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]: Unsatisfied dependency expressed through method 'modifyResponseBodyGatewayFilterFactory' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.http.codec.ServerCodecConfigurer' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2020-03-16 18:54:48.749  INFO 5900 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2020-03-16 18:54:48.754  WARN 5900 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
2020-03-16 18:54:48.771  INFO 5900 --- [  restartedMain] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-03-16 18:54:48.930 ERROR 5900 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method modifyResponseBodyGatewayFilterFactory in org.springframework.cloud.gateway.config.GatewayAutoConfiguration required a bean of type 'org.springframework.http.codec.ServerCodecConfigurer' that could not be found.


Action:

Consider defining a bean of type 'org.springframework.http.codec.ServerCodecConfigurer' in your configuration.


Process finished with exit code 0

Поэтому я попробовал предложение по этому вопросу bean of введите org.springframework.http.code c .ServerCodecConfigurer, который не может быть можно найти

, но он просто изменил ошибку на:

No qualifying bean of type 'org.springframework.core.convert.ConversionService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value="webFluxConversionService")}

Есть ли альтернативный подход вместо расширения KeycloakWebSecurityConfigurerAdapter или WebSecurityConfigurerAdapter или некоторого кода исправления чтобы по-прежнему иметь возможность предоставить пользовательский KeycloakConfigResolver, чтобы разрешить Multi Tenancy?

...