1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.proxy.handlers.http.basic;
21
22 import java.util.HashMap;
23 import java.util.List;
24 import java.util.Map;
25
26 import org.apache.mina.core.filterchain.IoFilter.NextFilter;
27 import org.apache.mina.proxy.ProxyAuthException;
28 import org.apache.mina.proxy.handlers.http.AbstractAuthLogicHandler;
29 import org.apache.mina.proxy.handlers.http.HttpProxyConstants;
30 import org.apache.mina.proxy.handlers.http.HttpProxyRequest;
31 import org.apache.mina.proxy.handlers.http.HttpProxyResponse;
32 import org.apache.mina.proxy.session.ProxyIoSession;
33 import org.apache.mina.proxy.utils.StringUtilities;
34 import org.apache.mina.util.Base64;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38
39
40
41
42
43
44
45 public class HttpBasicAuthLogicHandler extends AbstractAuthLogicHandler {
46 private final static Logger logger = LoggerFactory
47 .getLogger(HttpBasicAuthLogicHandler.class);
48
49 public HttpBasicAuthLogicHandler(final ProxyIoSession proxyIoSession)
50 throws ProxyAuthException {
51 super(proxyIoSession);
52
53 if (request == null || !(request instanceof HttpProxyRequest)) {
54 throw new IllegalArgumentException(
55 "request parameter should be a non null HttpProxyRequest instance");
56 }
57
58 HttpProxyRequest req = (HttpProxyRequest) request;
59 req.checkRequiredProperty(HttpProxyConstants.USER_PROPERTY);
60 req.checkRequiredProperty(HttpProxyConstants.PWD_PROPERTY);
61 }
62
63 @Override
64 public void doHandshake(final NextFilter nextFilter)
65 throws ProxyAuthException {
66 logger.debug(" doHandshake()");
67
68 if (step > 0) {
69 throw new ProxyAuthException("Authentication request already sent");
70 }
71
72
73 HttpProxyRequest req = (HttpProxyRequest) request;
74 Map<String, List<String>> headers = req.getHeaders() != null ? req
75 .getHeaders() : new HashMap<String, List<String>>();
76
77 String username = req.getProperties().get(
78 HttpProxyConstants.USER_PROPERTY);
79 String password = req.getProperties().get(
80 HttpProxyConstants.PWD_PROPERTY);
81
82 StringUtilities.addValueToHeader(headers, "Proxy-Authorization",
83 "Basic " + createAuthorization(username, password), true);
84
85 StringUtilities.addValueToHeader(headers, "Keep-Alive",
86 HttpProxyConstants.DEFAULT_KEEP_ALIVE_TIME, true);
87 StringUtilities.addValueToHeader(headers, "Proxy-Connection",
88 "keep-Alive", true);
89 req.setHeaders(headers);
90
91 writeRequest(nextFilter, req);
92 step++;
93 }
94
95
96
97
98 public static String createAuthorization(final String username,
99 final String password) {
100 return new String(Base64.encodeBase64((username + ":" + password)
101 .getBytes()));
102 }
103
104 @Override
105 public void handleResponse(final HttpProxyResponse response)
106 throws ProxyAuthException {
107 if (response.getStatusCode() != 407) {
108 throw new ProxyAuthException("Received error response code ("
109 + response.getStatusLine() + ").");
110 }
111 }
112 }