1 16 package org.mortbay.http; 17 18 import java.io.IOException ; 19 import java.security.Principal ; 20 21 import javax.net.ssl.SSLSocket; 22 23 import org.apache.commons.logging.Log; 24 import org.mortbay.log.LogFactory; 25 26 27 35 public class ClientCertAuthenticator implements Authenticator 36 { 37 private static Log log = LogFactory.getLog(ClientCertAuthenticator.class); 38 39 private int _maxHandShakeSeconds =60; 40 41 42 public ClientCertAuthenticator() 43 { 44 log.warn("Client Cert Authentication is EXPERIMENTAL"); 45 } 46 47 48 public int getMaxHandShakeSeconds() 49 { 50 return _maxHandShakeSeconds; 51 } 52 53 54 58 public void setMaxHandShakeSeconds(int maxHandShakeSeconds) 59 { 60 _maxHandShakeSeconds = maxHandShakeSeconds; 61 } 62 63 64 70 public Principal authenticate(UserRealm realm, 71 String pathInContext, 72 HttpRequest request, 73 HttpResponse response) 74 throws IOException 75 { 76 java.security.cert.X509Certificate [] certs = 77 (java.security.cert.X509Certificate []) 78 request.getAttribute("javax.servlet.request.X509Certificate"); 79 80 if (response!=null && (certs==null || certs.length==0 || certs[0]==null)) 81 { 82 84 Object s = HttpConnection.getHttpConnection().getConnection(); 86 if (!(s instanceof SSLSocket)) 87 return null; 88 SSLSocket socket = (SSLSocket)s; 89 90 if (!socket.getNeedClientAuth()) 91 { 92 socket.setNeedClientAuth(true); 94 socket.startHandshake(); 95 96 for (int i=(_maxHandShakeSeconds*4);i-->0;) 101 { 102 certs = (java.security.cert.X509Certificate []) 103 request.getAttribute("javax.servlet.request.X509Certificate"); 104 if (certs!=null && certs.length>0 && certs[0]!=null) 105 break; 106 try{Thread.sleep(250);} catch (Exception e) {break;} 107 } 108 } 109 } 110 111 if (certs==null || certs.length==0 || certs[0]==null) 112 return null; 113 114 Principal principal = certs[0].getSubjectDN(); 115 if (principal==null) 116 principal=certs[0].getIssuerDN(); 117 String username=principal==null?"clientcert":principal.getName(); 118 119 Principal user = realm.authenticate(username,certs,request); 120 121 request.setAuthType(SecurityConstraint.__CERT_AUTH); 122 if (user!=null) 123 request.setAuthUser(user.getName()); 124 request.setUserPrincipal(user); 125 return user; 126 } 127 128 129 public String getAuthMethod() 130 { 131 return SecurityConstraint.__CERT_AUTH; 132 } 133 134 } 135 | Popular Tags |