eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

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

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

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 – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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.

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.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

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 – LSS – NPI (cat=Security/Spring Security)
announcement - icon

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

eBook Jackson – NPI EA – 3 (cat = Jackson)