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

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

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 object. Also, 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 object. The 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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW