Wednesday 13 December 2017

How to Get Client Certificate from HttpServletRequest

In HTTP SSL authentication, client send its valid certificate to server to check authenticity. Server validates the request and allow access to resources if authentication is successful.

In this post, I am going to show you, how to read the ssl certitificate information that comes as value of request header filed 'ssl_client_cert'.

Step 1: Read the certificate information.
String certificateInfo = request.getHeader(ssl_client_cert);

Step 2: Create input stream to the certificateInfo.
InputStream is = new ByteArrayInputStream(Base64.getDecoder().decode(certificateInfo)

Step 3: Convert the stream to X509 certificate.
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(is);

CertUtil.java
package com.sample.util;

import java.io.InputStream;
import java.security.cert.CertificateFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.util.Base64;
import java.security.cert.X509Certificate;

/**
 * 
 * Utility class to read the certificate information from the request header
 * 'ssl_client_cert'.
 * 
 * If request is null (or) do not have header value 'ssl_client_cert' it returns
 * null, else return X509Certificate. In exceptional cases it returns null.
 * 
 * @author Krishna
 *
 */
public class CertUtil {
 private static final String SSL_CLIENT_CERT_HEADER = "ssl_client_cert";

 /**
  * 
  * @param request
  * @return
  */
 public X509Certificate getCertificate(HttpServletRequest request) {
  if (request == null) {
   return null;
  }

  /* Read the certificate information from the header 'ssl_client_cert' */
  String certificateInfo = request.getHeader(SSL_CLIENT_CERT_HEADER);

  if (certificateInfo == null || certificateInfo.isEmpty()) {
   return null;
  }

  try (InputStream is = new ByteArrayInputStream(Base64.getDecoder().decode(certificateInfo))) {
   CertificateFactory cf = CertificateFactory.getInstance("X.509");
   X509Certificate cert = (X509Certificate) cf.generateCertificate(is);
   return cert;
  } catch (Exception e) {
   return null;
  }
 }
}

No comments:

Post a Comment