DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Spring Boot Timeout Handling With RestClient, WebClient, and RestTemplate
  • Composing Custom Annotations in Spring
  • 10 Ways To Keep Your Java Application Safe and Secure
  • Using Swagger for Creating a PingFederate Admin API Java Wrapper

Trending

  • MySQL Instant DDL: Metadata Locks, Waiting Writers, and Query Pileups
  • Delegated Transport, Forked Authorization: Where Chat and AI-Agent Integrations Actually Break
  • Two AI Agents, One Database: Solving Concurrent Updates With Optimistic Locking
  • Microsoft Fabric Throttling: Diagnose Before You Scale

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Use Client Certificate Authentication With Java and RestTemplate

Use Client Certificate Authentication With Java and RestTemplate

Learn more about client certification authentication with Java and Spring's RestTemplate.

By 
Nayden Gochev
·
May. 15, 19 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
120.2K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

As a follow up of the http://gochev.blogspot.com/2019/04/convert-pfx-certificate-to-jks-p12-crt.html, we now have a keystore and a truststore (if anyone needs). And, we will use this keystore to send client-side authentication using Spring's RestTemplate.

First, copy your keystore.jks and truststore.jks in your classpath; no one wants absolute paths, right?

According to the JSSE reference guide from Oracle, the difference between truststore and keystore, in case you are not aware, is:

TrustManager: Determines whether the remote authentication credentials (and thus, the connection) should be trusted.
KeyManager: Determines which authentication credentials to send to the remote host.

The magic happens in the creation of SSLContext. Keep in mind that Spring Boot has a nice RestTemplateBuilder, but I will not use it because someone might have an older version or, like me, might just use plain, old, amazing Spring.

If you just want to use the keystore:

final String allPassword = "123456";

SSLContext sslContext = SSLContextBuilder

                .create()

                .loadKeyMaterial(ResourceUtils.getFile("classpath:keystore.jks"),

                                    allPassword.toCharArray(), allPassword.toCharArray())

                .build();


Or, if you just want to use the truststore:

final String allPassword = "123456";

SSLContext sslContext = SSLContextBuilder

                .create()

                .loadTrustMaterial(ResourceUtils.getFile("classpath:truststore.jks"), allPassword.toCharArray())

                .build();


I guess you know how to use both if you want to IGNORE the truststore certificate checking and trust ALL certificates (might be handy for testing purposes and localhost)

final String allPassword = "123456";

TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

SSLContext sslContext = SSLContextBuilder

                .create()

                .loadTrustMaterial(ResourceUtils.getFile("classpath:truststore.jks"), allPassword.toCharArray())

                .loadTrustMaterial(null, acceptingTrustStrategy) //accept all

                .build();


Once you have the sslContext, you simply:

HttpClient client = HttpClients.custom()

                                .setSSLContext(sslContext)

                                .build();



HttpComponentsClientHttpRequestFactory requestFactory =

                new HttpComponentsClientHttpRequestFactory();



requestFactory.setHttpClient(client);



RestTemplate restTemplate = new RestTemplate(requestFactory);


And voila, now, each time you make a get/post or exchange with your restTemplate, you will send the client-side certificate.

Full example (the "tests" version) that sends the client-side certificate and ignores the SSL certificate

private RestTemplate getRestTemplateClientAuthentication()

                throws IOException, UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException,

                KeyStoreException, KeyManagementException {



    final String allPassword = "123456";

    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

    SSLContext sslContext = SSLContextBuilder

                    .create()

                    .loadKeyMaterial(ResourceUtils.getFile("classpath:keystore.jks"),

                                        allPassword.toCharArray(), allPassword.toCharArray())

//.loadTrustMaterial(ResourceUtils.getFile("classpath:truststore.jks"), allPassword.toCharArray())

                    .loadTrustMaterial(null, acceptingTrustStrategy)

                    .build();



    HttpClient client = HttpClients.custom()

                                    .setSSLContext(sslContext)

                                    .build();



    HttpComponentsClientHttpRequestFactory requestFactory =

                    new HttpComponentsClientHttpRequestFactory();



    requestFactory.setHttpClient(client);



    RestTemplate restTemplate = new RestTemplate(requestFactory);



    return restTemplate;

}


Hope this comes in handy for someone!

authentication Java (programming language) resttemplate

Published at DZone with permission of Nayden Gochev. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot Timeout Handling With RestClient, WebClient, and RestTemplate
  • Composing Custom Annotations in Spring
  • 10 Ways To Keep Your Java Application Safe and Secure
  • Using Swagger for Creating a PingFederate Admin API Java Wrapper

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook