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.testing.async;
28
29 import java.io.IOException;
30 import java.nio.ByteBuffer;
31 import java.nio.charset.StandardCharsets;
32 import java.util.ArrayList;
33 import java.util.List;
34 import java.util.concurrent.atomic.AtomicReference;
35
36 import org.apache.hc.client5.testing.auth.AuthResult;
37 import org.apache.hc.client5.testing.auth.AuthenticationHandler;
38 import org.apache.hc.client5.testing.auth.Authenticator;
39 import org.apache.hc.client5.testing.auth.BasicAuthenticationHandler;
40 import org.apache.hc.core5.http.ContentType;
41 import org.apache.hc.core5.http.EntityDetails;
42 import org.apache.hc.core5.http.Header;
43 import org.apache.hc.core5.http.HttpException;
44 import org.apache.hc.core5.http.HttpHeaders;
45 import org.apache.hc.core5.http.HttpRequest;
46 import org.apache.hc.core5.http.HttpResponse;
47 import org.apache.hc.core5.http.HttpStatus;
48 import org.apache.hc.core5.http.NameValuePair;
49 import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
50 import org.apache.hc.core5.http.message.BasicHttpResponse;
51 import org.apache.hc.core5.http.message.BasicNameValuePair;
52 import org.apache.hc.core5.http.nio.AsyncResponseProducer;
53 import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
54 import org.apache.hc.core5.http.nio.CapacityChannel;
55 import org.apache.hc.core5.http.nio.DataStreamChannel;
56 import org.apache.hc.core5.http.nio.ResponseChannel;
57 import org.apache.hc.core5.http.nio.entity.BasicAsyncEntityProducer;
58 import org.apache.hc.core5.http.nio.support.BasicResponseProducer;
59 import org.apache.hc.core5.http.protocol.HttpContext;
60 import org.apache.hc.core5.net.URIAuthority;
61 import org.apache.hc.core5.util.Args;
62
63 public class AuthenticatingAsyncDecorator implements AsyncServerExchangeHandler {
64
65 private final AsyncServerExchangeHandler exchangeHandler;
66 private final AuthenticationHandler<String> authenticationHandler;
67 private final Authenticator authenticator;
68 private final AtomicReference<AsyncResponseProducer> responseProducerRef;
69
70
71
72
73 public AuthenticatingAsyncDecorator(final AsyncServerExchangeHandler exchangeHandler,
74 final AuthenticationHandler<String> authenticationHandler,
75 final Authenticator authenticator) {
76 this.exchangeHandler = Args.notNull(exchangeHandler, "Request handler");
77 this.authenticationHandler = Args.notNull(authenticationHandler, "Authentication handler");
78 this.authenticator = Args.notNull(authenticator, "Authenticator");
79 this.responseProducerRef = new AtomicReference<>();
80 }
81
82 public AuthenticatingAsyncDecorator(final AsyncServerExchangeHandler exchangeHandler, final Authenticator authenticator) {
83 this(exchangeHandler, new BasicAuthenticationHandler(StandardCharsets.US_ASCII), authenticator);
84 }
85
86 protected void customizeUnauthorizedResponse(final HttpResponse unauthorized) {
87 }
88
89 @Override
90 public void handleRequest(
91 final HttpRequest request,
92 final EntityDetails entityDetails,
93 final ResponseChannel responseChannel,
94 final HttpContext context) throws HttpException, IOException {
95 final Header h = request.getFirstHeader(HttpHeaders.AUTHORIZATION);
96 final String challengeResponse = h != null ? authenticationHandler.extractAuthToken(h.getValue()) : null;
97
98 final URIAuthority authority = request.getAuthority();
99 final String requestUri = request.getRequestUri();
100
101 final AuthResult authResult = authenticator.perform(authority, requestUri, challengeResponse);
102 final Header expect = request.getFirstHeader(HttpHeaders.EXPECT);
103 final boolean expectContinue = expect != null && "100-continue".equalsIgnoreCase(expect.getValue());
104
105 if (authResult.isSuccess()) {
106 if (expectContinue) {
107 responseChannel.sendInformation(new BasicClassicHttpResponse(HttpStatus.SC_CONTINUE), context);
108 }
109 exchangeHandler.handleRequest(request, entityDetails, responseChannel, context);
110 } else {
111 final HttpResponse unauthorized = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED);
112 final List<NameValuePair> challengeParams = new ArrayList<>();
113 final String realm = authenticator.getRealm(authority, requestUri);
114 if (realm != null) {
115 challengeParams.add(new BasicNameValuePair("realm", realm));
116 }
117 if (authResult.hasParams()) {
118 challengeParams.addAll(authResult.getParams());
119 }
120 final String challenge = authenticationHandler.challenge(challengeParams);
121 unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, challenge);
122 customizeUnauthorizedResponse(unauthorized);
123
124 final AsyncResponseProducer responseProducer = new BasicResponseProducer(
125 unauthorized,
126 new BasicAsyncEntityProducer("Unauthorized", ContentType.TEXT_PLAIN));
127 responseProducerRef.set(responseProducer);
128 responseProducer.sendResponse(responseChannel, context);
129 }
130
131 }
132
133 @Override
134 public final void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
135 final AsyncResponseProducer responseProducer = responseProducerRef.get();
136 if (responseProducer == null) {
137 exchangeHandler.updateCapacity(capacityChannel);
138 } else {
139 capacityChannel.update(Integer.MAX_VALUE);
140 }
141 }
142
143 @Override
144 public final void consume(final ByteBuffer src) throws IOException {
145 final AsyncResponseProducer responseProducer = responseProducerRef.get();
146 if (responseProducer == null) {
147 exchangeHandler.consume(src);
148 }
149 }
150
151 @Override
152 public final void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
153 final AsyncResponseProducer responseProducer = responseProducerRef.get();
154 if (responseProducer == null) {
155 exchangeHandler.streamEnd(trailers);
156 }
157 }
158
159 @Override
160 public final int available() {
161 final AsyncResponseProducer responseProducer = responseProducerRef.get();
162 if (responseProducer == null) {
163 return exchangeHandler.available();
164 } else {
165 return responseProducer.available();
166 }
167 }
168
169 @Override
170 public final void produce(final DataStreamChannel channel) throws IOException {
171 final AsyncResponseProducer responseProducer = responseProducerRef.get();
172 if (responseProducer == null) {
173 exchangeHandler.produce(channel);
174 } else {
175 responseProducer.produce(channel);
176 }
177 }
178
179 @Override
180 public final void failed(final Exception cause) {
181 try {
182 exchangeHandler.failed(cause);
183 final AsyncResponseProducer dataProducer = responseProducerRef.getAndSet(null);
184 if (dataProducer != null) {
185 dataProducer.failed(cause);
186 }
187 } finally {
188 releaseResources();
189 }
190 }
191
192 @Override
193 public final void releaseResources() {
194 exchangeHandler.releaseResources();
195 final AsyncResponseProducer dataProducer = responseProducerRef.getAndSet(null);
196 if (dataProducer != null) {
197 dataProducer.releaseResources();
198 }
199 }
200
201 }