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

Authentication is the fundamental aspect of designing a secure microservice. We can implement authentication in various ways, like using user-based credentials, certificates, or token-based.

In this tutorial, we’ll learn how to setup authentication for service-to-service communication. We’ll implement the solution using Spring Security.

2. Introduction to Custom Authentication

Using an identity provider or password database might not always be feasible, as private microservices don’t need user-based interaction. However, we should still protect the application against any invalid requests rather than just rely on network security.

In such a scenario, we can devise a simple authentication technique by using a custom shared secret header. The application will validate the request against the pre-configured request header.

We should also enable TLS in the application to secure the shared secret over the network.

We may also need to ensure a few endpoints work without any authentication, such as health checks or error endpoints.

3. Example Application

Let’s imagine we need to build a microservice with a few REST APIs.

3.1. Maven Dependencies

First, we’ll start by creating a Spring Boot Web project and include a few Spring dependencies.

Let’s add spring-boot-starter-web, spring-boot-starter-security, spring-boot-starter-test  and rest-assured dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
</dependency>

3.2. Implement the REST Controllers

Our application has two endpoints, one endpoint accessible with a shared secret header and another endpoint accessible to all in the network.

First, let’s implement the APIController class with a /hello endpoint:

@GetMapping(path = "/api/hello")
public String hello(){
    return "hello";
}

Then, we’ll implement the health endpoint in the HealthCheckController class:

@GetMapping(path = "/health")
public String getHealthStatus() {
   return "OK";
}

4. Implement the Custom Authentication With Spring Security

Spring Security provides several in-built filter classes to implement authentication. We can also override the built-in filter class or use an authentication provider to implement a custom solution.

We’ll configure the application to register an AuthenticationFilter into the filter chain.

4.1. Implement the Authentication Filter

To implement a header-based authentication, we can use the RequestHeaderAuthenticationFilter class. The RequestHeaderAuthenticationFilter is a pre-authenticated filter that obtains the principal from a request header. As with any pre-auth scenarios, we’ll need to convert the proof of authentication into a user with a role.

The RequestHeaderAuthenticationFilter sets the Principal object with the request header. Internally, it’ll create a PreAuthenticedAuthenticationToken object using the Principal and Credential from the request header and pass the token to the authentication manager.

Let’s add the RequestHeaderAuthenticationFilter Bean in the SecurityConfig class:

@Bean
public RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter() {
    RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
    filter.setPrincipalRequestHeader("x-auth-secret-key");
    filter.setExceptionIfHeaderMissing(false);
    filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/api/**"));
    filter.setAuthenticationManager(authenticationManager());

    return filter;
}

In the above code, the x-auth-header-key header is added as the Principal objectAlso, the AuthenticationManager object is included to delegate the actual authentication.

We should note that the filter is enabled for the endpoints matching with the /api/** path.

4.2. Setup the Authentication Manager

Now, we’ll create the AuthenticationManager and pass a custom AuthenticationProvider object, which we’ll create later:

@Bean
protected AuthenticationManager authenticationManager() {
    return new ProviderManager(Collections.singletonList(requestHeaderAuthenticationProvider));
}

4.3. Configure the Authentication Provider

To implement the custom authentication provider, we’ll implement the AuthenticationProvider interface.

Let’s override the authenticate method defined in the AuthenticationProvider interface:

public class RequestHeaderAuthenticationProvider implements AuthenticationProvider {
     
    @Value("${api.auth.secret}")
    private String apiAuthSecret;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String authSecretKey = String.valueOf(authentication.getPrincipal());

        if(StringUtils.isBlank(authSecretKey) || !authSecretKey.equals(apiAuthSecret) {
            throw new BadCredentialsException("Bad Request Header Credentials");
        }

        return new PreAuthenticatedAuthenticationToken(authentication.getPrincipal(), null, new ArrayList<>());
    }
}

In the above code, the authSecretkey value matched with the Principal. In case the header is not valid, the method throws a BadCredentialsException.

On successful authentication, it’ll return the fully authenticated PreAuthenticatedAuthenticationToken objectThe PreAuthenticatedAuthenticationToken object can be treated as a user for role-based authorization.

Also, we’ll need to override the supports method defined in the AuthenticationProvider interface:

@Override
public boolean supports(Class<?> authentication) {
    return authentication.equals(PreAuthenticatedAuthenticationToken.class);
}

The supports method checks for the Authentication class type supported by this authentication provider.

4.4. Configure Filter With Spring Security

To enable Spring Security in the application, we’ll add the @EnableWebSecurity annotation. Also, we need to create a SecurityFilterChain object.

Also, Spring Security enables CORS and CSRF protection by default. As this application is only accessible by internal microservice, we’ll disable the CORS and CSRF protection.

Let’s include the above RequestHeaderAuthenticationFilter in the SecurityFilterChain:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
       http.cors(Customizer.withDefaults()).csrf(AbstractHttpConfigurer::disable)
          .sessionManagement(httpSecuritySessionManagementConfigurer -> httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
          .addFilterAfter(requestHeaderAuthenticationFilter(), HeaderWriterFilter.class)
          .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry
                      .requestMatchers("/api/**").authenticated());

        return http.build();
    }
}

We should note that the session management is set as STATELESS since the application is accessed internally.

4.5. Exclude Health Endpoint From Authentication

Using the antMatcher’s permitAll method, we can exclude any public endpoints from authentication and authorization.

Let’s add the /health endpoint in the above filterchain method to exclude from authentication:

.requestMatchers(HttpMethod.GET, "/health").permitAll()
.exceptionHandling(httpSecurityExceptionHandlingConfigurer -> 
       httpSecurityExceptionHandlingConfigurer.authenticationEntryPoint((request, response, authException) -> 
                                                          response.sendError(HttpServletResponse.SC_UNAUTHORIZED)));

We should note that the exception handling is configured to include the authenticationEntryPoint for returning 401 Unauthorized status.

5. Implement Integration Tests for the API

With TestRestTemplate, we’ll implement the integration tests for the endpoints.

First, let’s implement the test by passing a valid x-auth-secret-key header to the /hello endpoint:

HttpHeaders headers = new HttpHeaders();
headers.add("x-auth-secret-key", "test-secret");

ResponseEntity<String> response = restTemplate.exchange(new URI("http://localhost:8080/app/api"),
  HttpMethod.GET, new HttpEntity<>(headers), String.class);

assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("hello", response.getBody());

Then, let’s implement a test by passing an invalid header:

HttpHeaders headers = new HttpHeaders();
headers.add("x-auth-secret-key", "invalid-secret");

ResponseEntity<String> response = restTemplate.exchange(new URI("http://localhost:8080/app/api"),
  HttpMethod.GET, new HttpEntity<>(headers), String.class);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());

Finally, we’ll test the /health endpoint without adding any header:

HttpHeaders headers = new HttpHeaders();
ResponseEntity<String> response = restTemplate.exchange(new URI(HEALTH_CHECK_ENDPOINT),
  HttpMethod.GET, new HttpEntity<>(headers), String.class);

assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("OK", response.getBody());

As expected, the authentication works for the required endpoint. The /health endpoint is accessible without the header authentication.

6. Conclusion

In this article, we’ve learned how using a custom header with a shared secret authentication helps to secure service-to-service communication.

We’ve also seen how to implement shared secret-based header authentication using a combination of the RequestHeaderAuthenticationFilter and a custom authentication provider.

As always, the example code can be found over 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.