Course – LSS – NPI (cat=Spring Security)
announcement - icon

If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:

>> LEARN SPRING SECURITY

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-data-redis</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 {
}

Note that for the gateway service, we need to use a different annotation namely @EnableRedisWebSession.

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:discPassword@localhost: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:discPassword@localhost: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:

@EnableWebFluxSecurity
@Configuration
public class SecurityConfig {
    @Bean
    public MapReactiveUserDetailsService userDetailsService() {
        UserDetails user = User.withUsername("user")
            .password(passwordEncoder().encode("password"))
            .roles("USER")
            .build();
        UserDetails adminUser = User.withUsername("admin")
            .password(passwordEncoder().encode("admin"))
            .roles("ADMIN")
            .build();
        return new MapReactiveUserDetailsService(user, adminUser);
    }
    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http.formLogin()
            .authenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler("/home/index.html"))
            .and().authorizeExchange()
            .pathMatchers("/book-service/**", "/rating-service/**", "/login*", "/")
            .permitAll()
            .pathMatchers("/eureka/**").hasRole("ADMIN")
            .anyExchange().authenticated().and()
            .logout().and().csrf().disable().httpBasic(withDefaults());
        return http.build();
    }
}

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 have to add @EnableRedisWebSession:

@Configuration
@EnableRedisWebSession
public class SessionConfig {}

The Spring Cloud Gateway filter automatically 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:discPassword@localhost:8082/eureka/

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

management.security.sessions=always

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

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.

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:

@EnableWebSecurity
@Configuration
public class SecurityConfig {
    @Autowired
    public void registerAuthProvider(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication();
    }
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http.authorizeHttpRequests((auth) -> auth.antMatchers(HttpMethod.GET, "/books").permitAll()
                .antMatchers(HttpMethod.GET, "/books/*").permitAll()
                .antMatchers(HttpMethod.POST, "/books").hasRole("ADMIN")
                .antMatchers(HttpMethod.PATCH, "/books/*").hasRole("ADMIN")
                .antMatchers(HttpMethod.DELETE, "/books/*").hasRole("ADMIN"))
                .csrf().disable().build();
    }
}

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:discPassword@localhost: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:

@EnableWebSecurity
@Configuration
public class SecurityConfig {
    @Bean
    public UserDetailsService users() {
        return new InMemoryUserDetailsManager();
    }
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity.authorizeHttpRequests((auth) -> auth.regexMatchers("^/ratings\\?bookId.*$")
                .authenticated()
                .antMatchers(HttpMethod.POST, "/ratings").authenticated()
                .antMatchers(HttpMethod.PATCH, "/ratings/*").hasRole("ADMIN")
                .antMatchers(HttpMethod.DELETE, "/ratings/*").hasRole("ADMIN")
                .antMatchers(HttpMethod.GET, "/ratings").hasRole("ADMIN")
                .anyRequest().authenticated()).httpBasic()
                .and().csrf().disable().build();
    }
}

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:discPassword@localhost: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 + "/home/index.html", 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 Spring Cloud Gateway 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.

Course – LSS (cat=Security/Spring Security)

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

>> CHECK OUT THE COURSE
res – Security (video) (cat=Security/Spring Security)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.