Spring Cloud - Sécurisation des services

1. Vue d'ensemble

Dans l'article précédent, Spring Cloud - Bootstrapping, nous avons créé une application Spring Cloud de base . Cet article montre comment le sécuriser.

Nous utiliserons naturellement Spring Security pour partager des sessions à l'aide de Spring Session et Redis . Cette méthode est simple à mettre en place et facile à étendre à de nombreux scénarios d'entreprise. Si vous n'êtes pas familier avec Spring Session , consultez cet article.

Le partage de sessions nous donne la possibilité de connecter les utilisateurs à notre service de passerelle et de propager cette authentification à tout autre service de notre système.

Si vous n'êtes pas familier avec Redis ou Spring Security , c'est une bonne idée de passer rapidement en revue ces sujets à ce stade. Bien qu'une grande partie de l'article soit prête à être copiée-collée pour une application, rien ne remplace la compréhension de ce qui se passe sous le capot.

Pour une introduction à Redis, lisez ce didacticiel. Pour une introduction à Spring Security, lisez spring-security-login, role-and-privilege-for-spring-security-registration et spring-security-session. Pour avoir une compréhension complète de Spring Security, jetez un œil à la classe learn-spring-security-the-master.

2. Configuration de Maven

Commençons par ajouter la dépendance spring-boot-starter-security à chaque module du système:

 org.springframework.boot spring-boot-starter-security 

Comme nous utilisons la gestion des dépendances Spring , nous pouvons omettre les versions des dépendances spring-boot-starter .

Dans un deuxième temps, modifions le pom.xml de chaque application avec les dépendances spring-session, spring-boot-starter-data-redis:

 org.springframework.session spring-session   org.springframework.boot spring-boot-starter-data-redis 

Seulement quatre de nos applications lieront en session de printemps : découverte , la passerelle , le service de la livre et de service de notation .

Ensuite, ajoutez une classe de configuration de session dans les trois services dans le même répertoire que le fichier d'application principal:

@EnableRedisHttpSession public class SessionConfig extends AbstractHttpSessionApplicationInitializer { }

Enfin, ajoutez ces propriétés aux trois fichiers * .properties de notre référentiel git:

spring.redis.host=localhost spring.redis.port=6379

Passons maintenant à la configuration spécifique au service.

3. Sécurisation du service de configuration

Le service de configuration contient des informations sensibles souvent liées aux connexions de base de données et aux clés API. Nous ne pouvons pas compromettre ces informations, alors plongeons-nous et sécurisons ce service.

Ajoutons des propriétés de sécurité au fichier application.properties dans src / main / resources du service de configuration:

eureka.client.serviceUrl.defaultZone= //discUser:[email protected]:8082/eureka/ security.user.name=configUser security.user.password=configPassword security.user.role=SYSTEM

Cela configurera notre service pour se connecter avec découverte. De plus, nous configurons notre sécurité avec le fichier application.properties .

Configurons maintenant notre service de découverte.

4. Sécurisation du service de découverte

Notre service de découverte contient des informations sensibles sur l'emplacement de tous les services de l'application. Il enregistre également les nouvelles instances de ces services.

Si des clients malveillants y accèdent, ils apprendront l'emplacement réseau de tous les services de notre système et pourront enregistrer leurs propres services malveillants dans notre application. Il est essentiel que le service de découverte soit sécurisé.

4.1. Configuration de la sécurité

Ajoutons un filtre de sécurité pour protéger les points de terminaison que les autres services utiliseront:

@Configuration @EnableWebSecurity @Order(1) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) { auth.inMemoryAuthentication().withUser("discUser") .password("discPassword").roles("SYSTEM"); } @Override protected void configure(HttpSecurity http) { http.sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.ALWAYS) .and().requestMatchers().antMatchers("/eureka/**") .and().authorizeRequests().antMatchers("/eureka/**") .hasRole("SYSTEM").anyRequest().denyAll().and() .httpBasic().and().csrf().disable(); } }

Cela mettra en place notre service avec un utilisateur « SYSTEM ». Il s'agit d'une configuration de base de Spring Security avec quelques rebondissements. Jetons un coup d'œil à ces rebondissements:

  • @Order (1) - dit à Spring de câbler d'abord ce filtre de sécurité afin qu'il soit tenté avant tout autre
  • .sessionCreationPolicy - indique à Spring de toujours créer une session lorsqu'un utilisateur se connecte à ce filtre
  • .requestMatchers – limits what endpoints this filter applies to

The security filter, we just set up, configures an isolated authentication environment that pertains to the discovery service only.

4.2. Securing Eureka Dashboard

Since our discovery application has a nice UI to view currently registered services, let's expose that using a second security filter and tie this one into the authentication for the rest of our application. Keep in mind that no @Order() tag means that this is the last security filter to be evaluated:

@Configuration public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) { http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER) .and().httpBasic().disable().authorizeRequests() .antMatchers(HttpMethod.GET, "/").hasRole("ADMIN") .antMatchers("/info", "/health").authenticated().anyRequest() .denyAll().and().csrf().disable(); } }

Add this configuration class within the SecurityConfig class. This will create a second security filter that will control access to our UI. This filter has a few unusual characteristics, let's look at those:

  • httpBasic().disable() – tells spring security to disable all authentication procedures for this filter
  • sessionCreationPolicy – we set this to NEVER to indicate we require the user to have already authenticated prior to accessing resources protected by this filter

This filter will never set a user session and relies on Redis to populate a shared security context. As such, it is dependent on another service, the gateway, to provide authentication.

4.3. Authenticating With Config Service

In the discovery project, let's append two properties to the bootstrap.properties in src/main/resources:

spring.cloud.config.username=configUser spring.cloud.config.password=configPassword

These properties will let the discovery service authenticate with the config service on startup.

Let's update our discovery.properties in our Git repository

eureka.client.serviceUrl.defaultZone= //discUser:[email protected]:8082/eureka/ eureka.client.register-with-eureka=false eureka.client.fetch-registry=false

We have added basic authentication credentials to our discovery service to allow it to communicate with the config service. Additionally, we configure Eureka to run in standalone mode by telling our service not to register with itself.

Let's commit the file to the git repository. Otherwise, the changes will not be detected.

5. Securing Gateway Service

Our gateway service is the only piece of our application we want to expose to the world. As such it will need security to ensure that only authenticated users can access sensitive information.

5.1. Security Configuration

Let's create a SecurityConfig class like our discovery service and overwrite the methods with this content:

@Autowired public void configureGlobal(AuthenticationManagerBuilder auth) { auth.inMemoryAuthentication().withUser("user").password("password") .roles("USER").and().withUser("admin").password("admin") .roles("ADMIN"); } @Override protected void configure(HttpSecurity http) { http.authorizeRequests().antMatchers("/book-service/books") .permitAll().antMatchers("/eureka/**").hasRole("ADMIN") .anyRequest().authenticated().and().formLogin().and() .logout().permitAll().logoutSuccessUrl("/book-service/books") .permitAll().and().csrf().disable(); }

This configuration is pretty straightforward. We declare a security filter with form login that secures a variety of endpoints.

The security on /eureka/** is to protect some static resources we will serve from our gateway service for the Eureka status page. If you are building the project with the article, copy the resource/static folder from the gateway project on Github to your project.

Now we modify the @EnableRedisHttpSession annotation on our config class:

@EnableRedisHttpSession( redisFlushMode = RedisFlushMode.IMMEDIATE)

We set the flush mode to immediate to persist any changes on the session immediately. This helps in preparing the authentication token for redirection.

Finally, let's add a ZuulFilter that will forward our authentication token after login:

@Component public class SessionSavingZuulPreFilter extends ZuulFilter { @Autowired private SessionRepository repository; @Override public boolean shouldFilter() { return true; } @Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); HttpSession httpSession = context.getRequest().getSession(); Session session = repository.getSession(httpSession.getId()); context.addZuulRequestHeader( "Cookie", "SESSION=" + httpSession.getId()); return null; } @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 0; } }

This filter will grab the request as it is redirected after login and add the session key as a cookie in the header. This will propagate authentication to any backing service after login.

5.2. Authenticating With Config and Discovery Service

Let us add the following authentication properties to the bootstrap.properties file in src/main/resources of the gateway service:

spring.cloud.config.username=configUser spring.cloud.config.password=configPassword eureka.client.serviceUrl.defaultZone= //discUser:[email protected]:8082/eureka/

Next, let's update our gateway.properties in our Git repository

management.security.sessions=always zuul.routes.book-service.path=/book-service/** zuul.routes.book-service.sensitive-headers=Set-Cookie,Authorization hystrix.command.book-service.execution.isolation.thread .timeoutInMilliseconds=600000 zuul.routes.rating-service.path=/rating-service/** zuul.routes.rating-service.sensitive-headers=Set-Cookie,Authorization hystrix.command.rating-service.execution.isolation.thread .timeoutInMilliseconds=600000 zuul.routes.discovery.path=/discovery/** zuul.routes.discovery.sensitive-headers=Set-Cookie,Authorization zuul.routes.discovery.url=//localhost:8082 hystrix.command.discovery.execution.isolation.thread .timeoutInMilliseconds=600000

We have added session management to always generate sessions because we only have one security filter we can set that in the properties file. Next, we add our Redis host and server properties.

In addition, we added a route that will redirect requests to our discovery service. Since a standalone discovery service will not register with itself we must locate that service with a URL scheme.

We can remove the serviceUrl.defaultZone property from the gateway.properties file in our configuration git repository. This value is duplicated in the bootstrap file.

Let's commit the file to the Git repository, otherwise, the changes will not be detected.

6. Securing Book Service

The book service server will hold sensitive information controlled by various users. This service must be secured to prevent leaks of protected information in our system.

6.1. Security Configuration

To secure our book service we will copy the SecurityConfig class from the gateway and overwrite the method with this content:

@Override protected void configure(HttpSecurity http) { http.httpBasic().disable().authorizeRequests() .antMatchers("/books").permitAll() .antMatchers("/books/*").hasAnyRole("USER", "ADMIN") .authenticated().and().csrf().disable(); }

6.2. Properties

Add these properties to the bootstrap.properties file in src/main/resources of the book service:

spring.cloud.config.username=configUser spring.cloud.config.password=configPassword eureka.client.serviceUrl.defaultZone= //discUser:[email protected]:8082/eureka/

Let's add properties to our book-service.properties file in our git repository:

management.security.sessions=never

We can remove the serviceUrl.defaultZone property from the book-service.properties file in our configuration git repository. This value is duplicated in the bootstrap file.

Remember to commit these changes so the book-service will pick them up.

7. Securing Rating Service

The rating service also needs to be secured.

7.1. Security Configuration

To secure our rating service we will copy the SecurityConfig class from the gateway and overwrite the method with this content:

@Override protected void configure(HttpSecurity http) { http.httpBasic().disable().authorizeRequests() .antMatchers("/ratings").hasRole("USER") .antMatchers("/ratings/all").hasAnyRole("USER", "ADMIN").anyRequest() .authenticated().and().csrf().disable(); }

We can delete the configureGlobal() method from the gateway service.

7.2. Properties

Add these properties to the bootstrap.properties file in src/main/resources of the rating service:

spring.cloud.config.username=configUser spring.cloud.config.password=configPassword eureka.client.serviceUrl.defaultZone= //discUser:[email protected]:8082/eureka/

Let's add properties to our rating-service.properties file in our git repository:

management.security.sessions=never

We can remove the serviceUrl.defaultZone property from the rating-service.properties file in our configuration git repository. This value is duplicated in the bootstrap file.

Remember to commit these changes so the rating service will pick them up.

8. Running and Testing

Start Redis and all the services for the application: config, discovery, gateway, book-service, and rating-service. Now let's test!

First, let's create a test class in our gateway project and create a method for our test:

public class GatewayApplicationLiveTest { @Test public void testAccess() { ... } }

Next, let's set up our test and validate that we can access our unprotected /book-service/books resource by adding this code snippet inside our test method:

TestRestTemplate testRestTemplate = new TestRestTemplate(); String testUrl = "//localhost:8080"; ResponseEntity response = testRestTemplate .getForEntity(testUrl + "/book-service/books", String.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); Assert.assertNotNull(response.getBody());

Run this test and verify the results. If we see failures confirm that the entire application started successfully and that configurations were loaded from our configuration git repository.

Now let's test that our users will be redirected to log in when visiting a protected resource as an unauthenticated user by appending this code to the end of the test method:

response = testRestTemplate .getForEntity(testUrl + "/book-service/books/1", String.class); Assert.assertEquals(HttpStatus.FOUND, response.getStatusCode()); Assert.assertEquals("//localhost:8080/login", response.getHeaders() .get("Location").get(0));

Run the test again and confirm that it succeeds.

Next, let's actually log in and then use our session to access the user protected result:

MultiValueMap form = new LinkedMultiValueMap(); form.add("username", "user"); form.add("password", "password"); response = testRestTemplate .postForEntity(testUrl + "/login", form, String.class); 

now, let us extract the session from the cookie and propagate it to the following request:

String sessionCookie = response.getHeaders().get("Set-Cookie") .get(0).split(";")[0]; HttpHeaders headers = new HttpHeaders(); headers.add("Cookie", sessionCookie); HttpEntity httpEntity = new HttpEntity(headers); 

and request the protected resource:

response = testRestTemplate.exchange(testUrl + "/book-service/books/1", HttpMethod.GET, httpEntity, String.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); Assert.assertNotNull(response.getBody());

Run the test again to confirm the results.

Now, let's try to access the admin section with the same session:

response = testRestTemplate.exchange(testUrl + "/rating-service/ratings/all", HttpMethod.GET, httpEntity, String.class); Assert.assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());

Run the test again, and as expected we are restricted from accessing admin areas as a plain old user.

The next test will validate that we can log in as the admin and access the admin protected resource:

form.clear(); form.add("username", "admin"); form.add("password", "admin"); response = testRestTemplate .postForEntity(testUrl + "/login", form, String.class); sessionCookie = response.getHeaders().get("Set-Cookie").get(0).split(";")[0]; headers = new HttpHeaders(); headers.add("Cookie", sessionCookie); httpEntity = new HttpEntity(headers); response = testRestTemplate.exchange(testUrl + "/rating-service/ratings/all", HttpMethod.GET, httpEntity, String.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); Assert.assertNotNull(response.getBody());

Our test is getting big! But we can see when we run it that by logging in as the admin we gain access to the admin resource.

Our final test is accessing our discovery server through our gateway. To do this add this code to the end of our test:

response = testRestTemplate.exchange(testUrl + "/discovery", HttpMethod.GET, httpEntity, String.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode());

Run this test one last time to confirm that everything is working. Success!!!

Did you miss that? Because we logged in on our gateway service and viewed content on our book, rating, and discovery services without having to log in on four separate servers!

By utilizing Spring Session to propagate our authentication object between servers we are able to log in once on the gateway and use that authentication to access controllers on any number of backing services.

9. Conclusion

Security in the cloud certainly becomes more complicated. But with the help of Spring Security and Spring Session, we can easily solve this critical issue.

Nous disposons désormais d'une application cloud sécurisée autour de nos services. En utilisant Zuul et Spring Session, nous pouvons connecter les utilisateurs à un seul service et propager cette authentification à l'ensemble de notre application. Cela signifie que nous pouvons facilement diviser notre application en domaines appropriés et sécuriser chacun d'entre eux comme bon nous semble.

Comme toujours, vous pouvez trouver le code source sur GitHub.