Partner – Trifork – NPI (cat=Spring Boot)
announcement - icon

Navigating the complexities of Spring can be difficult, even for seasoned developers.

If you need direct, practical help and guidance with your own Spring work, Trifork's CTO, Joris Kuipers, is running a closed-door call.

It's free, but it's limited to only 3 seats, so if you need it, I would join quickly and be sure to attend:

>>> CTO Spring Open Office Hour Session - Technical Guidance

With more than 15 years of leading custom software development projects involving Spring, Joris has gained a lot of real-world experience, and this call is about sharing and helping the community.


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 5:


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 and spring-boot-starter-test dependencies:


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:

public RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter() {
    RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
    filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/api/**"));

    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:

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 {
    private String apiAuthSecret;

    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:

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:

public class SecurityConfig {

    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
          .addFilterAfter(requestHeaderAuthenticationFilter(), HeaderWriterFilter.class)


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:

.exceptionHandling().authenticationEntryPoint((request, response, authException) ->

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 = 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 = 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 = 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 5:

res – Security (video) (cat=Security/Spring Security)
Inline Feedbacks
View all comments