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

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

Security is one of the most important aspects of any software application. It is a non-negotiable aspect. Mutual Transport Layer Security(mTLS) is one of the ways people use to secure their apps. In this article, we’ll learn how to make HTTP calls to a server when mTLS is enabled.

We’ll start with an introduction to mTLS, then we’ll learn how to set up Nginx server with mTLS. Lastly, we’ll use Java clients like HttpsURLConnection and HttpClient to make calls to the server.

 2. What Is mTLS?

Mutual TLS(mTLS) is a security protocol that extends standard TLS by requiring both client and server to present and verify X.509 certificates, enabling two-way authentication. Unlike regular TLS, where only the server proves its identity, mTLS ensures that the client is also verified, making it ideal for high-security environments.

It’s commonly used to secure internal communication between services, authenticate users or devices without passwords, and enforce zero trust security models in micro-services, APIs, and enterprise systems.

3. Setting up Nginx With mTLS

To set up Nginx with mTLS, we’re going to generate the required certificates for the server and client. After the certificates are ready, we’ll configure Nginx with these certificates to enable mTLS.

3.1. Generate Certificates

For mTLS, we need to generate the certificates for the server and the client. We’re going to use self-signed certificates for simplicity. To do this, we’ll need our own certificate authority(CA).

So, let’s set up the certificate authority:

openssl genrsa -des3 -out ca.key 4096
openssl rsa -in ca.key -out ca.key
openssl req -new -x509 -days 3650 -key ca.key -subj "/CN=*.server.hostname" -out ca.crt

The above commands generate a self-signed SSL certificate. First, a 4096-bit RSA private key, viz. ca.key, is created and encrypted using a passphrase with DES3. Then, the passphrase is removed from the key, outputting an unencrypted version of the same key. Finally, a self-signed X.509 certificate ca.crt is generated using the unencrypted private key, valid for ten years, and subject common name set to *.server.hostname. 

Now, our certificate authority(CA) is ready. We can create server and client certificates using this CA. First, let’s create the server private key and certificate.

The first step is to generate the private key:

printf test > server_passphrase.txt
openssl genrsa -des3 -passout file:server_passphrase.txt -out server.key 1024

Just like earlier commands, the above command generates the server private key viz. server.key.

Now, we can generate a certificate signing request(CSR) for the server:

openssl req -new -passin file:server_passphrase.txt -key server.key -subj "/CN=*.server.hostname" -out server.csr

Here, we’ll sign the CSR with the certificate authority that we created earlier:

openssl x509 -req -days 365 -in server.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out server.crt

Now, the certificate for the server viz. server.crt is ready. Let’s create certificates for the client.

We’re going to use the same CA for the client as well:

printf test > client_passphrase.txt
openssl genrsa -des3 -passout file:client_passphrase.txt -out client.key 2048
openssl rsa -passin file:client_passphrase.txt -in client.key -out client.key
openssl req -new -key client.key -subj "/CN=*.client.hostname" -out client.csr
openssl x509 -req -days 365 -in client.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out client.crt

Just like the server, we’ve used the same commands for the client as well to generate keys and certificates. The client.key and client.crt are the private key and certificate, respectively.

3.2. Add mTLS to Nginx

Here, we’re going to configure Nginx with the configurations to serve mTLS requests:

http {
    server {
        listen 443 ssl;
        server_name  test.server.hostname;
        ssl_password_file /etc/nginx/certs/server_passphrase.txt;
        ssl_certificate /etc/nginx/certs/server.crt;
        ssl_certificate_key /etc/nginx/certs/server.key;

        ssl_client_certificate /etc/nginx/certs/ca.crt;
        ssl_verify_client on;
        ssl_verify_depth  3;
 
        ssl_protocols             TLSv1 TLSv1.1 TLSv1.2;

        location /ping {
            proxy_pass http://localhost:9091;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
}

This Nginx configuration sets up an HTTPS server on port 443 with mTLS enabled, requiring clients to present valid certificates signed by a trusted CA. It uses server.crt and server.key as the server’s credentials, reads the private key passphrase from passphrase.txt, and verifies client certificates against ca.crt with a verification depth of 3. The /ping endpoint proxies requests to a local service on port 9091, forwarding the original host and client IP headers for context.

4. Add mTLS to Java Clients

Before calling the above-created Nginx Server with mTLS request, we first need to build SSL configurations for our Java clients. So, let’s learn how to build an SSLContext.

4.1. Build SSLContext

Let’s learn how to create SSLContext step by step.

First, we’ll convert the client private key from PEM format to DER:

openssl pkcs8 -topk8 -inform PEM -outform PEM -in client.key -out client.key.pkcs8 -nocrypt

By using a local Nginx service for this example, we need to disable the hostname verification:

final Properties props = System.getProperties();
props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.TRUE.toString());

The next step is to load the client keys into Java code and create a KeyManagerFactory:

String privateKeyPath = "/etc/crts/client.key.pkcs8";
String publicKeyPath = "/etc/crts/client.crt";

final byte[] publicData = Files.readAllBytes(Path.of(publicKeyPath));
final byte[] privateData = Files.readAllBytes(Path.of(privateKeyPath));

String privateString = new String(privateData, Charset.defaultCharset())
  .replace("-----BEGIN PRIVATE KEY-----", "")
  .replaceAll(System.lineSeparator(), "")
  .replace("-----END PRIVATE KEY-----", "");

byte[] encoded = Base64.getDecoder().decode(privateString);

final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
final Collection<? extends Certificate> chain = certificateFactory.generateCertificates(new ByteArrayInputStream(publicData));

Key key = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(encoded));

KeyStore clientKeyStore = KeyStore.getInstance("jks");
final char[] pwdChars = "test".toCharArray();
clientKeyStore.load(null, null);
clientKeyStore.setKeyEntry("test", key, pwdChars, chain.toArray(new Certificate[0]));

KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(clientKeyStore, pwdChars);

In the above code, bytes are read from the certificate and key files to construct a certificate chain from the public key and a private key instance. These are used to create a Java KeyStore containing both the certificate and private key. Finally, a KeyManagerFactory is initialised with the KeyStore to enable secure SSL/TLS communication.

Due to using self-signed certificates, we need to use a TrustManager that will accept them. The following TrustManager will accept all certificates presented from the server:

TrustManager[] acceptAllTrustManager = { new X509TrustManager() {
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }

    public void checkClientTrusted(
        X509Certificate[] certs, String authType) {
    }

    public void checkServerTrusted(
        X509Certificate[] certs, String authType) {
    }
 }};

Now, we can initialise an SSLContext with the KeyManagerFactory that we created above:

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), acceptAllTrustManager, new java.security.SecureRandom());

4.2. Using Java Clients

Till now, we’ve set up Nginx server with mTLS on and know how to build an SSLContext. Let’s test all these one by one. First of all, we’ll write a unit test to verify the SSLContext:

@Test
public void whenPrivateAndPublicKeysAreGiven_thenAnSSLContextShouldBeCreated(){
    SSLContext sslContext = SslContextBuilder.buildSslContext();
    Assertions.assertThat(sslContext).isNotNull();
}

Since our SSLContext is ready and working, we can now make mTLS calls to Nginx using Java Clients.

Before testing with Java clients, we need to make sure that we’ve our Nginx up and running. Also we’ve to run a server on port 9091 that serves requests on /ping. We can easily create by following this article. Both components are required in order to pass these tests.

We’ll first test with HttpClient:

@Test
public void whenWeExecuteMutualTLSCallToNginxServerWithHttpClient_thenItShouldReturnStatusOK() {
    SSLContext sslContext = SslContextBuilder.buildSslContext();
    HttpClient client = HttpClient.newBuilder()
      .sslContext(sslContext)
      .build();

    HttpRequest exactRequest = HttpRequest.newBuilder()
      .uri(URI.create("https://localhost/ping"))
      .GET()
      .build();

    HttpResponse<String> response = client.sendAsync(exactRequest, HttpResponse.BodyHandlers.ofString())
      .join();
    Assertions.assertThat(response).isNotNull();
    Assertions.assertThat(response.statusCode()).isEqualTo(200);
}

The above test will call Nginx, and it will route /ping to the server that is running at port 9091. We’ll receive a 200 code, which means that our request had a successful mTLS connection.

Now, we’ll test with HttpsURLConnection:

@Test
public void whenWeExecuteMutualTLSCallToNginxServerWithHttpURLConnection_thenItShouldReturnNonNullResponse() {
    SSLContext sslContext = SslContextBuilder.buildSslContext();
    HttpsURLConnection httpsURLConnection = (HttpsURLConnection) new URL("https://127.0.0.1/ping")
      .openConnection();
    httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    httpsURLConnection.setHostnameVerifier(HostNameVerifierBuilder.getAllHostsValid());
    InputStream inputStream = httpsURLConnection.getInputStream();
    String response = new String(inputStream.readAllBytes(), Charset.defaultCharset());
    Assertions.assertThat(response).isNotNull();
}

Just like the above test, this will execute the same flow.

5. Conclusion

In this article, we learned about mTLS by setting up a certificate authority and generating certificates for both the server and clients.

We then configured an Nginx server to use mTLS for secure communication. On the client side, we loaded the certificates in a Java application by creating a KeyManagerFactory, TrustManager, and initialising an SSLContext.

Finally, we tested SSLConext and executed mTLS calls with Java clients such as HttpClient and HttpURLConnection.

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)