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 public class HttpBasicAuthLogicHandler extends AbstractAuthLogicHandler {
45 private static final Logger LOGGER = LoggerFactory.getLogger(HttpBasicAuthLogicHandler.class);
46
47
48
49
50
51
52
53 public HttpBasicAuthLogicHandler(final ProxyIoSession proxyIoSession) throws ProxyAuthException {
54 super(proxyIoSession);
55
56 ((HttpProxyRequest) request).checkRequiredProperties(HttpProxyConstants.USER_PROPERTY,
57 HttpProxyConstants.PWD_PROPERTY);
58 }
59
60
61
62
63 @Override
64 public void doHandshake(final NextFilter nextFilter) throws ProxyAuthException {
65 if (LOGGER.isDebugEnabled()) {
66 LOGGER.debug(" doHandshake()");
67 }
68
69 if (step > 0) {
70 throw new ProxyAuthException("Authentication request already sent");
71 }
72
73
74 HttpProxyRequest./../../../../org/apache/mina/proxy/handlers/http/HttpProxyRequest.html#HttpProxyRequest">HttpProxyRequest req = (HttpProxyRequest) request;
75 Map<String, List<String>> headers = req.getHeaders() != null ? req.getHeaders()
76 : new HashMap<String, List<String>>();
77
78 String username = req.getProperties().get(HttpProxyConstants.USER_PROPERTY);
79 String password = req.getProperties().get(HttpProxyConstants.PWD_PROPERTY);
80
81 StringUtilities.addValueToHeader(headers, "Proxy-Authorization",
82 "Basic " + createAuthorization(username, password), true);
83
84 addKeepAliveHeaders(headers);
85 req.setHeaders(headers);
86
87 writeRequest(nextFilter, req);
88 step++;
89 }
90
91
92
93
94
95
96
97
98 public static String createAuthorization(final String username, final String password) {
99 return new String(Base64.encodeBase64((username + ":" + password).getBytes()));
100 }
101
102
103
104
105 @Override
106 public void handleResponse(final HttpProxyResponse response) throws ProxyAuthException {
107 if (response.getStatusCode() != 407) {
108 throw new ProxyAuthException("Received error response code (" + response.getStatusLine() + ").");
109 }
110 }
111 }