javasslssl-certificateclient-certificatesjsse

Java SSLSocket find out if client sent a certificate


My application allows authenticated and non-authenticated TLS connections and in the code, I need to distinguish between them (just as in authenticated and non-authenticated HTTPS sessions). Is there a way to find out if a Java SSLSocket connection (on the server) was established from a client with a client certificate? And if so, can I see the CN= of the client certificate?


Solution

  • As noted in the comments,

    try {
        Certificate cert = socket.getSession().getPeerCertificate();
        // we get here if the client *was* authenticated
        return cert;
    } catch (SSLPeerUnverifiedException e) {
        // we get here if the client *was not* authenticated
        return null;
    }
    

    seems to be what you need.