View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.hc.client5.testing.async;
28  
29  import java.io.IOException;
30  import java.nio.ByteBuffer;
31  import java.util.ArrayList;
32  import java.util.List;
33  import java.util.concurrent.atomic.AtomicReference;
34  
35  import org.apache.hc.client5.testing.auth.AuthResult;
36  import org.apache.hc.client5.testing.auth.AuthenticationHandler;
37  import org.apache.hc.client5.testing.auth.Authenticator;
38  import org.apache.hc.client5.testing.auth.BasicAuthenticationHandler;
39  import org.apache.hc.core5.http.ContentType;
40  import org.apache.hc.core5.http.EntityDetails;
41  import org.apache.hc.core5.http.Header;
42  import org.apache.hc.core5.http.HttpException;
43  import org.apache.hc.core5.http.HttpHeaders;
44  import org.apache.hc.core5.http.HttpRequest;
45  import org.apache.hc.core5.http.HttpResponse;
46  import org.apache.hc.core5.http.HttpStatus;
47  import org.apache.hc.core5.http.NameValuePair;
48  import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
49  import org.apache.hc.core5.http.message.BasicHttpResponse;
50  import org.apache.hc.core5.http.message.BasicNameValuePair;
51  import org.apache.hc.core5.http.nio.AsyncResponseProducer;
52  import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
53  import org.apache.hc.core5.http.nio.CapacityChannel;
54  import org.apache.hc.core5.http.nio.DataStreamChannel;
55  import org.apache.hc.core5.http.nio.ResponseChannel;
56  import org.apache.hc.core5.http.nio.entity.BasicAsyncEntityProducer;
57  import org.apache.hc.core5.http.nio.support.BasicResponseProducer;
58  import org.apache.hc.core5.http.protocol.HttpContext;
59  import org.apache.hc.core5.net.URIAuthority;
60  import org.apache.hc.core5.util.Args;
61  
62  public class AuthenticatingAsyncDecorator implements AsyncServerExchangeHandler {
63  
64      private final AsyncServerExchangeHandler exchangeHandler;
65      private final AuthenticationHandler<String> authenticationHandler;
66      private final Authenticator authenticator;
67      private final AtomicReference<AsyncResponseProducer> responseProducerRef;
68  
69      /**
70       * @since 5.3
71       */
72      public AuthenticatingAsyncDecorator(final AsyncServerExchangeHandler exchangeHandler,
73                                          final AuthenticationHandler<String> authenticationHandler,
74                                          final Authenticator authenticator) {
75          this.exchangeHandler = Args.notNull(exchangeHandler, "Request handler");
76          this.authenticationHandler = Args.notNull(authenticationHandler, "Authentication handler");
77          this.authenticator = Args.notNull(authenticator, "Authenticator");
78          this.responseProducerRef = new AtomicReference<>();
79      }
80  
81      public AuthenticatingAsyncDecorator(final AsyncServerExchangeHandler exchangeHandler, final Authenticator authenticator) {
82          this(exchangeHandler, new BasicAuthenticationHandler(), authenticator);
83      }
84  
85      protected void customizeUnauthorizedResponse(final HttpResponse unauthorized) {
86      }
87  
88      @Override
89      public void handleRequest(
90              final HttpRequest request,
91              final EntityDetails entityDetails,
92              final ResponseChannel responseChannel,
93              final HttpContext context) throws HttpException, IOException {
94          final Header h = request.getFirstHeader(HttpHeaders.AUTHORIZATION);
95          final String challengeResponse = h != null ? authenticationHandler.extractAuthToken(h.getValue()) : null;
96  
97          final URIAuthority authority = request.getAuthority();
98          final String requestUri = request.getRequestUri();
99  
100         final AuthResult authResult = authenticator.perform(authority, requestUri, challengeResponse);
101         final Header expect = request.getFirstHeader(HttpHeaders.EXPECT);
102         final boolean expectContinue = expect != null && "100-continue".equalsIgnoreCase(expect.getValue());
103 
104         if (authResult.isSuccess()) {
105             if (expectContinue) {
106                 responseChannel.sendInformation(new BasicClassicHttpResponse(HttpStatus.SC_CONTINUE), context);
107             }
108             exchangeHandler.handleRequest(request, entityDetails, responseChannel, context);
109         } else {
110             final HttpResponse unauthorized = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED);
111             final List<NameValuePair> challengeParams = new ArrayList<>();
112             final String realm = authenticator.getRealm(authority, requestUri);
113             if (realm != null) {
114                 challengeParams.add(new BasicNameValuePair("realm", realm));
115             }
116             if (authResult.hasParams()) {
117                 challengeParams.addAll(authResult.getParams());
118             }
119             final String challenge = authenticationHandler.challenge(challengeParams);
120             unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, challenge);
121             customizeUnauthorizedResponse(unauthorized);
122 
123             final AsyncResponseProducer responseProducer = new BasicResponseProducer(
124                     unauthorized,
125                     new BasicAsyncEntityProducer("Unauthorized", ContentType.TEXT_PLAIN));
126             responseProducerRef.set(responseProducer);
127             responseProducer.sendResponse(responseChannel, context);
128         }
129 
130     }
131 
132     @Override
133     public final void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
134         final AsyncResponseProducer responseProducer = responseProducerRef.get();
135         if (responseProducer == null) {
136             exchangeHandler.updateCapacity(capacityChannel);
137         } else {
138             capacityChannel.update(Integer.MAX_VALUE);
139         }
140     }
141 
142     @Override
143     public final void consume(final ByteBuffer src) throws IOException {
144         final AsyncResponseProducer responseProducer = responseProducerRef.get();
145         if (responseProducer == null) {
146             exchangeHandler.consume(src);
147         }
148     }
149 
150     @Override
151     public final void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
152         final AsyncResponseProducer responseProducer = responseProducerRef.get();
153         if (responseProducer == null) {
154             exchangeHandler.streamEnd(trailers);
155         }
156     }
157 
158     @Override
159     public final int available() {
160         final AsyncResponseProducer responseProducer = responseProducerRef.get();
161         if (responseProducer == null) {
162             return exchangeHandler.available();
163         } else {
164             return responseProducer.available();
165         }
166     }
167 
168     @Override
169     public final void produce(final DataStreamChannel channel) throws IOException {
170         final AsyncResponseProducer responseProducer = responseProducerRef.get();
171         if (responseProducer == null) {
172             exchangeHandler.produce(channel);
173         } else {
174             responseProducer.produce(channel);
175         }
176     }
177 
178     @Override
179     public final void failed(final Exception cause) {
180         try {
181             exchangeHandler.failed(cause);
182             final AsyncResponseProducer dataProducer = responseProducerRef.getAndSet(null);
183             if (dataProducer != null) {
184                 dataProducer.failed(cause);
185             }
186         } finally {
187             releaseResources();
188         }
189     }
190 
191     @Override
192     public final void releaseResources() {
193         exchangeHandler.releaseResources();
194         final AsyncResponseProducer dataProducer = responseProducerRef.getAndSet(null);
195         if (dataProducer != null) {
196             dataProducer.releaseResources();
197         }
198     }
199 
200 }