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