1 31 32 package org.apache.commons.httpclient.server; 33 34 import java.io.IOException ; 35 36 import org.apache.commons.httpclient.Credentials; 37 import org.apache.commons.httpclient.Header; 38 import org.apache.commons.httpclient.auth.AuthenticationException; 39 import org.apache.commons.httpclient.auth.BasicScheme; 40 import org.apache.commons.httpclient.auth.HttpAuthenticator; 41 import org.apache.commons.httpclient.auth.MalformedChallengeException; 42 43 50 public class ProxyAuthRequestHandler implements HttpRequestHandler { 51 private Credentials credentials; 52 53 57 public ProxyAuthRequestHandler(Credentials creds) { 58 if (creds == null) throw new IllegalArgumentException ("Credentials can not be null"); 59 this.credentials = creds; 60 } 61 62 public boolean processRequest(SimpleHttpServerConnection conn) 63 throws IOException { 64 Header[] headers = conn.getHeaders(); 65 Header clientAuth = findHeader(headers, HttpAuthenticator.PROXY_AUTH_RESP); 66 if (clientAuth != null) { 67 boolean ok = checkAuthorization(clientAuth); 68 if (ok) conn.connectionKeepAlive(); 69 return !ok; 70 } else { 71 performHandshake(conn); 72 } 73 return true; 74 } 75 76 79 private void performHandshake(SimpleHttpServerConnection conn) throws IOException { 80 Header challenge = createChallenge(); 81 ResponseWriter out = conn.getWriter(); 82 out.println("HTTP/1.1 407 Proxy Authentication Required"); 83 out.print(challenge.toExternalForm()); 84 out.print(new Header("Proxy-Connection", "Keep-Alive").toExternalForm()); 85 out.print(new Header("Content-Length", "0").toExternalForm()); 86 out.println(); 87 out.flush(); 88 conn.connectionKeepAlive(); 89 } 90 91 95 private Header createChallenge() { 96 Header header = new Header(); 97 header.setName(HttpAuthenticator.PROXY_AUTH); 98 String challenge = "basic realm=test"; 100 header.setValue(challenge); 101 return header; 102 } 103 104 109 private boolean checkAuthorization(Header clientAuth) { 110 BasicScheme scheme; 112 try { 113 scheme = new BasicScheme("basic realm=test"); 114 String expectedAuthString = scheme.authenticate(credentials, null, null); 115 return expectedAuthString.equals(clientAuth.getValue()); 116 } catch (MalformedChallengeException e) { 117 e.printStackTrace(); 119 } catch (AuthenticationException e) { 120 e.printStackTrace(); 122 } 123 return false; 124 } 125 126 private Header findHeader(Header[] headers, String name) { 127 for(int i=0; i<headers.length; i++) { 128 Header header = headers[i]; 129 if (header.getName().equalsIgnoreCase(name)) return header; 130 } 131 return null; 132 } 133 134 } 135 | Popular Tags |