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 DefaultUserTokenHandlererTokenHandler.html#DefaultUserTokenHandler">DefaultUserTokenHandler INSTANCE = new DefaultUserTokenHandler();
63
64 @Override
65 public Object getUserToken(final HttpRoute route, final HttpContext context) {
66
67 final HttpClientContext clientContext = HttpClientContext.adapt(context);
68
69 final HttpRequest request = clientContext.getRequest();
70 final HttpHost target = request != null ? new HttpHost(request.getScheme(), request.getAuthority()) : route.getTargetHost();
71
72 final AuthExchange targetAuthExchange = clientContext.getAuthExchange(target);
73 if (targetAuthExchange != null) {
74 final Principal authPrincipal = getAuthPrincipal(targetAuthExchange);
75 if (authPrincipal != null) {
76 return authPrincipal;
77 }
78 }
79 final HttpHost proxy = route.getProxyHost();
80 if (proxy != null) {
81 final AuthExchange proxyAuthExchange = clientContext.getAuthExchange(proxy);
82 if (proxyAuthExchange != null) {
83 final Principal authPrincipal = getAuthPrincipal(proxyAuthExchange);
84 if (authPrincipal != null) {
85 return authPrincipal;
86 }
87 }
88 }
89 final SSLSession sslSession = clientContext.getSSLSession();
90 if (sslSession != null) {
91 return sslSession.getLocalPrincipal();
92 }
93 return null;
94 }
95
96 private static Principal getAuthPrincipal(final AuthExchange authExchange) {
97 final AuthScheme scheme = authExchange.getAuthScheme();
98 if (scheme != null && scheme.isConnectionBased()) {
99 return scheme.getPrincipal();
100 }
101 return null;
102 }
103
104 }