Paul Deason
Paul Deason

Reputation: 21

Java Manual Client Certificate Authentication

As part of a Java web app I'm looking to implement client authentication through a browser certificate. I have been able to locate information on how to generate and install the certificates on the client and server.

In terms of access, all the information I can find seems to be about configuring access to a particular path e.g. www.mydomain.com/securearea and letting the server handle access.

However, I want to implement custom behaviour depending on whether the user presents a valid client certificate or not, rather than a blanket access block. Essentially I want to be able to create a method like hasValidClientCertificate()

Unfortunately I'm unable to find any reference as to how I can programatically check if the client has a valid certificate in Java. I'm using Tomcat. This isn't my strong area so would be very grateful for any tips or advice.

Many thanks for your time

Paul

Upvotes: 2

Views: 448

Answers (1)

Michael
Michael

Reputation: 10319

You need to perform couple of steps

1) Configure tomcat to perform client certificate authentication (in the server.xml):

<Connector port="8443" 
protocol="HTTP/1.1" 
SSLEnabled="true"          
maxThreads="150" 
minSpareThreads="25" 
maxSpareThreads="75"
enableLookups="false" 
disableUploadTimeout="true"
acceptCount="100" 
keyAlias="tomcat"
debug="0" 
scheme="https" 
secure="true"
clientAuth="want" 
sslProtocol="TLS" 
keystoreFile="server.keystore" keystorePass="changeit" 
truststoreFile="trust.keystore" truststorePass="changeit"/>

Clarification from http://tomcat.apache.org/tomcat-7.0-doc/config/http.html regarding clientAuth attribute:

set to want if you want the SSL stack to request a client Certificate, but not fail if one isn't presented.

Please refer to Tomcat authentication for better explanation how to configure Tomcat for SSL: http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html

2) Implement your hasValidClientCertificate() using the following code:

X509Certificate[] crts = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
if (crts!= null && crts.length > 0) {
    return true;        
}

3) If you need to access to the user certificate please access

X509Certificate userCert = crts [0];

Upvotes: 1

Related Questions