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 three of our applications will tie into Spring Session: discovery, gateway, and resource.
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: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:
@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("/resource/hello/cloud") .permitAll().antMatchers("/eureka/**").hasRole("ADMIN") .anyRequest().authenticated().and().formLogin().and() .logout().permitAll().logoutSuccessUrl("/resource/hello/cloud") .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 resource 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 zuul.routes.resource.path=/resource/** zuul.routes.resource.sensitive-headers=Set-Cookie,Authorization hystrix.command.resource.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 Resource Service
The resource server will hold sensitive information controlled by various users. This service must be secured to prevent the leak of protected information in our system.
6.1. Security Configuration
To secure our resource server 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("/hello/cloud").permitAll() .antMatchers("/hello/user").hasAnyRole("USER", "ADMIN") .antMatchers("/hello/admin").hasRole("ADMIN").anyRequest() .authenticated().and().csrf().disable(); }
We can delete the configureGlobal() method from the gateway service.
6.2. Java Configuration
Next, let’s make add code in our main application class to test our security features. In ResourceApplication.java add:
@Value("${resource.user.returnString}") private String userReturnString; @Value("${resource.admin.returnString}") private String adminReturnString; @RequestMapping("/hello/user") public String getUserString() { return userReturnString; } @RequestMapping("/hello/admin") public String getAdminString() { return adminReturnString; }
6.3. Properties
Add these properties to the bootstrap.properties file in src/main/resources of the resource 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 resource.properties file in our git repository:
resource.user.returnString=hello cloud user resource.admin.returnString=hello cloud admin management.security.sessions=never
We can remove the serviceUrl.defaultZone property from the resource.properties file in our configuration git repository. This value is duplicated in the bootstrap file.
Remember to commit these changes so the resource service will pick them up.
7. Running and Testing
Start Redis and all the services for the application: config, discovery, resource, and gateway. 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 /resource/hello/cloud 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 + "/resource/hello/cloud", String.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); Assert.assertEquals("hello cloud", 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 + "/resource/hello/user", 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 + "/resource/hello/user", HttpMethod.GET, httpEntity, String.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); Assert.assertEquals("hello cloud user", 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 + "/resource/hello/admin", 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 + "/resource/hello/admin", HttpMethod.GET, httpEntity, String.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); Assert.assertEquals("hello cloud admin", 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, we viewed content on our resource service, and then viewed content on our discovery service without having to log in on three 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.
8. 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 user’s 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.