Can anybody provide me with a code sample to access rest service url secured with https using spring rest template.
I have the certificate, username and password. Basic Authentication is used on the server side and I want to create a client that can connect to that server using provided certificate, username and password (if needed).
This is a solution with no deprecated class or method : (Java 8 approved)
Here is what I ended up with for the similar problem. The idea is the same as in @Avi's answer, but I also wanted to avoid the static "System.setProperty("https.protocols", "TLSv1");", so that any adjustments won't affect the system. Inspired by an answer from here http://www.coderanch.com/t/637177/Security/Disabling-handshake-message-Java
One point from me. I used a mutual cert authentication with spring-boot microservices. The following is working for me, keys point here are keyManagerFactory.init(...) and sslcontext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom()) lines of code without them atleast for me things did not work. Certificates are packaged by PKCS12.
Here is some code that will give you the general idea.
You need to create a custom
ClientHttpRequestFactory
in order to trust the certificate. It looks like this:This is the implementation for
MyCustomClientHttpRequestFactory
:In this case my
serverInfo
object contains the thumbprint of the server. You need to implement theTrustManager
interface to get theSslThumbprintVerifier
or any other method you want to verify your certificate (you can also decide to also always returntrue
).The value
org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
allows all host names. If you need to verify the host name, you will need to implement it differently.I'm not sure about the user and password and how you implemented it. Often, you need to add a header to the
restTemplate
namedAuthorization
with a value that looks like this:Base: <encoded user+password>
. Theuser+password
must beBase64
encoded.