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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

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

  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques
  • Advancing Your Software Engineering Career in 2025
  • How Kubernetes Cluster Sizing Affects Performance and Cost Efficiency in Cloud Deployments
  • Designing a Java Connector for Software Integrations
  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 user avatar
Nayden Gochev
·
May. 15, 19 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
118.5K Views

Join the DZone community and get the full member experience.

Join For Free

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
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!