I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

In the previous article, Spring Cloud – Bootstrapping, we’ve built a basic Spring Cloud application. This article shows how to secure it.

We’ll naturally use Spring Security to share sessions using Spring Session and Redis. This method is simple to set up and easy to extend to many business scenarios. If you are unfamiliar with Spring Session, check out this article.

Sharing sessions gives us the ability to log users in our gateway service and propagate that authentication to any other service of our system.

If you’re unfamiliar with Redis or Spring Security, it’s a good idea to do a quick review of these topics at this point. While much of the article is copy-paste ready for an application, there is no replacement for understanding what happens under the hood.

For an introduction to Redis read this tutorial. For an introduction to Spring Security read spring-security-login, role-and-privilege-for-spring-security-registration, and spring-security-session. To get a complete understanding of Spring Security, have a look at the learn-spring-security-the-master-class.

2. Maven Setup

Let’s start by adding the spring-boot-starter-security dependency to each module in the system:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Because we use Spring dependency management we can omit the versions for spring-boot-starter dependencies.

As a second step, let’s modify the pom.xml of each application with spring-session, spring-boot-starter-data-redis dependencies:

<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Only four of our applications will tie into Spring Session: discovery, gateway, book-service, and rating-service.

Next, add a session configuration class in all three services in the same directory as the main application file:

@EnableRedisHttpSession
public class SessionConfig
  extends AbstractHttpSessionApplicationInitializer {
}

Last, add these properties to the three *.properties files in our git repository:

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

Now let’s jump into service specific configuration.

3. Securing Config Service

The config service contains sensitive information often related to database connections and API keys. We cannot compromise this information so let’s dive right in and secure this service.

Let us add security properties to the application.properties file in src/main/resources of the config service:

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

This will set up our service to login with discovery. In addition, we are configuring our security with the application.properties file.

Let’s now configure our discovery service.

4. Securing Discovery Service

Our discovery service holds sensitive information about the location of all the services in the application. It also registers new instances of those services.

If malicious clients gain access, they will learn network location of all the services in our system and be able to register their own malicious services into our application. It is critical that the discovery service is secured.

4.1. Security Configuration

Let’s add a security filter to protect the endpoints the other services will use:

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

This will set up our service with a ‘SYSTEM‘ user. This is a basic Spring Security configuration with a few twists. Let’s take a look at those twists:

  • @Order(1) – tells Spring to wire this security filter first so that it is attempted before any others
  • .sessionCreationPolicy – tells Spring to always create a session when a user logs in on this filter
  • .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=
  http://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=
  http://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=http://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=
  http://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=
  http://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 = "http://localhost:8080";

ResponseEntity<String> 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("http://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<String, String> 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<String> 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.

We now have a cloud application with security around our services. Using Zuul and Spring Session we can log users in only one service and propagate that authentication to our entire application. This means we can easily break our application into proper domains and secure each of them as we see fit.

As always you can find the source code on GitHub.

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS

newest oldest most voted
Notify of
B SRIDHAR
Guest
B SRIDHAR

Thanks for an interesting article on Securing Services in Spring Cloud. Please find my thoughts below. Instead of providing the config service credentials with every service wouldn’t it be better to have them in a shared application.properties in git repo. Also, the eureka url with credentials is needed by every service , so why shouldn’t that also be maintained in shared application.properties in git repo. Wouldn’t they make maintenance easier. Another query is regarding the High Availability of Eureka Service. In your article, you have used a standalone eureka service using config-first approach to fetch config from configuration service on… Read more »

B SRIDHAR
Guest
B SRIDHAR

You article is informative as always. I have a few thoughts. Wouldn’t it be better if we can move the secured eureka url with credentials and credentials needed for accessing config service (including config url) in a shared application.properties in git repo so that it can be maintained in single place. Can we have multiple eureka instances for High Availability and have every service register with the multiple eureka instances. Would it be better if we use ZUUL proxy endpoint for Eureka for service clients to register with a load balanced eureka instance and then have the registrations replicated across… Read more »

Sridhar
Guest
Sridhar

You article is informative as always. I have a few questions as below. Can the Eureka registration url used by service clients(along with its secure credentials) as well the the credentials for accessing the config service(including the config service url) be moved to the shared application configuration in git repo. In this way, whenever there is a change in one of them, we do not have to change in multiple locations. Also, can we have Eureka configuration externalized in config repo and have eureka fetch the same at startup. The downside I see with this approach is that the config… Read more »

Timothy Schimandle
Guest
Timothy Schimandle

Sridhar, Thanks for reading the tutorial. The reason we specify the eureka registration in the bootstrap.properties files is to locate the config server using eureka. You basically have to decide if your system is going to use eureka to access the config server or access the config server directly. I’ve opted for accessing it through eureka. In this instance the application must know the location of eureka before it has access to the config server to get shared properties. If you configure bootstrap.properties with for accessing the configuration server you could have the eureka information in the git repo. As… Read more »