1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package org.apache.hc.client5.http.impl;
28
29 import java.security.Principal;
30
31 import javax.net.ssl.SSLSession;
32
33 import org.apache.hc.client5.http.HttpRoute;
34 import org.apache.hc.client5.http.UserTokenHandler;
35 import org.apache.hc.client5.http.auth.AuthExchange;
36 import org.apache.hc.client5.http.auth.AuthScheme;
37 import org.apache.hc.client5.http.protocol.HttpClientContext;
38 import org.apache.hc.core5.annotation.Contract;
39 import org.apache.hc.core5.annotation.ThreadingBehavior;
40 import org.apache.hc.core5.http.HttpHost;
41 import org.apache.hc.core5.http.HttpRequest;
42 import org.apache.hc.core5.http.protocol.HttpContext;
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59 @Contract(threading = ThreadingBehavior.STATELESS)
60 public class DefaultUserTokenHandler implements UserTokenHandler {
61
62 public static final DefaultUserTokenHandler INSTANCE = new DefaultUserTokenHandler();
63
64 @Override
65 public Object getUserToken(final HttpRoute route, final HttpContext context) {
66 return getUserToken(route, null, context);
67 }
68
69 @Override
70 public Object getUserToken(final HttpRoute route, final HttpRequest request, final HttpContext context) {
71
72 final HttpClientContext clientContext = HttpClientContext.adapt(context);
73
74 final HttpHost target = request != null ? new HttpHost(request.getScheme(), request.getAuthority()) : route.getTargetHost();
75
76 final AuthExchange targetAuthExchange = clientContext.getAuthExchange(target);
77 if (targetAuthExchange != null) {
78 final Principal authPrincipal = getAuthPrincipal(targetAuthExchange);
79 if (authPrincipal != null) {
80 return authPrincipal;
81 }
82 }
83 final HttpHost proxy = route.getProxyHost();
84 if (proxy != null) {
85 final AuthExchange proxyAuthExchange = clientContext.getAuthExchange(proxy);
86 if (proxyAuthExchange != null) {
87 final Principal authPrincipal = getAuthPrincipal(proxyAuthExchange);
88 if (authPrincipal != null) {
89 return authPrincipal;
90 }
91 }
92 }
93 final SSLSession sslSession = clientContext.getSSLSession();
94 if (sslSession != null) {
95 return sslSession.getLocalPrincipal();
96 }
97 return null;
98 }
99
100 private static Principal getAuthPrincipal(final AuthExchange authExchange) {
101 final AuthScheme scheme = authExchange.getAuthScheme();
102 if (scheme != null && scheme.isConnectionBased()) {
103 return scheme.getPrincipal();
104 }
105 return null;
106 }
107
108 }