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.core5.http.nio.support;
28  
29  import java.io.IOException;
30  import java.nio.ByteBuffer;
31  import java.util.List;
32  
33  import org.apache.hc.core5.annotation.Contract;
34  import org.apache.hc.core5.annotation.ThreadingBehavior;
35  import org.apache.hc.core5.http.EntityDetails;
36  import org.apache.hc.core5.http.Header;
37  import org.apache.hc.core5.http.HttpException;
38  import org.apache.hc.core5.http.HttpHeaders;
39  import org.apache.hc.core5.http.HttpRequest;
40  import org.apache.hc.core5.http.HttpResponse;
41  import org.apache.hc.core5.http.HttpStatus;
42  import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
43  import org.apache.hc.core5.http.message.BasicHttpResponse;
44  import org.apache.hc.core5.http.nio.AsyncDataConsumer;
45  import org.apache.hc.core5.http.nio.AsyncEntityProducer;
46  import org.apache.hc.core5.http.nio.AsyncFilterChain;
47  import org.apache.hc.core5.http.nio.AsyncFilterHandler;
48  import org.apache.hc.core5.http.nio.CapacityChannel;
49  import org.apache.hc.core5.http.nio.entity.BasicAsyncEntityProducer;
50  import org.apache.hc.core5.http.protocol.HttpContext;
51  import org.apache.hc.core5.net.URIAuthority;
52  
53  /**
54   * Abstract asynchronous HTTP request filter that implements standard HTTP authentication handshake.
55   *
56   * @param <T> authorization token representation.
57   *
58   * @since 5.0
59   */
60  @Contract(threading = ThreadingBehavior.STATELESS)
61  public abstract class AbstractAsyncServerAuthFilter<T> implements AsyncFilterHandler {
62  
63      private final boolean respondImmediately;
64  
65      protected AbstractAsyncServerAuthFilter(final boolean respondImmediately) {
66          this.respondImmediately = respondImmediately;
67      }
68  
69      /**
70       * Parses authorization header value into an authentication token sent by the client
71       * as a response to an authentication challenge.
72       *
73       * @param authorizationValue the authorization header value.
74       * @param context the actual execution context.
75       * @return authorization token
76       */
77      protected abstract T parseChallengeResponse(String authorizationValue, HttpContext context) throws HttpException;
78  
79      /**
80       * Authenticates the client using the authentication token sent by the client
81       * as a response to an authentication challenge.
82       *
83       * @param challengeResponse the authentication token sent by the client
84       *                          as a response to an authentication challenge.
85       * @param authority the URI authority.
86       * @param requestUri the request URI.
87       * @param context the actual execution context.
88       * @return {@code true} if the client could be successfully authenticated {@code false} otherwise.
89       */
90      protected abstract boolean authenticate(T challengeResponse, URIAuthority authority, String requestUri, HttpContext context);
91  
92      /**
93       * Generates an authentication challenge in case of unsuccessful authentication.
94       *
95       * @param challengeResponse the authentication token sent by the client
96       *                          as a response to an authentication challenge
97       *                          or {@code null} if the client has not sent any.
98       * @param authority the URI authority.
99       * @param requestUri the request URI.
100      * @param context the actual execution context.
101      * @return an authorization challenge value.
102      */
103     protected abstract String generateChallenge(T challengeResponse, URIAuthority authority, String requestUri, HttpContext context);
104 
105     /**
106      * Generates response body for UNAUTHORIZED response.
107      *
108      * @param unauthorized the response to return as a result of authentication failure.
109      * @return the response content entity.
110      */
111     protected AsyncEntityProducer generateResponseContent(final HttpResponse unauthorized) {
112         return new BasicAsyncEntityProducer("Unauthorized");
113     }
114 
115     @Override
116     public final AsyncDataConsumer handle(
117             final HttpRequest request,
118             final EntityDetails entityDetails,
119             final HttpContext context,
120             final AsyncFilterChain.ResponseTrigger responseTrigger,
121             final AsyncFilterChain chain) throws HttpException, IOException {
122         final Header h = request.getFirstHeader(HttpHeaders.AUTHORIZATION);
123         final T challengeResponse = h != null ? parseChallengeResponse(h.getValue(), context) : null;
124 
125         final URIAuthority authority = request.getAuthority();
126         final String requestUri = request.getRequestUri();
127 
128         final boolean authenticated = authenticate(challengeResponse, authority, requestUri, context);
129         final Header expect = request.getFirstHeader(HttpHeaders.EXPECT);
130         final boolean expectContinue = expect != null && "100-continue".equalsIgnoreCase(expect.getValue());
131 
132         if (authenticated) {
133             if (expectContinue) {
134                 responseTrigger.sendInformation(new BasicClassicHttpResponse(HttpStatus.SC_CONTINUE));
135             }
136             return chain.proceed(request, entityDetails, context, responseTrigger);
137         }
138         final HttpResponse unauthorized = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED);
139         unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, generateChallenge(challengeResponse, authority, requestUri, context));
140         final AsyncEntityProducer responseContentProducer = generateResponseContent(unauthorized);
141         if (respondImmediately || expectContinue || entityDetails == null) {
142             responseTrigger.submitResponse(unauthorized, responseContentProducer);
143             return null;
144         }
145         return new AsyncDataConsumer() {
146 
147             @Override
148             public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
149                 capacityChannel.update(Integer.MAX_VALUE);
150             }
151 
152             @Override
153             public int consume(final ByteBuffer src) throws IOException {
154                 return Integer.MAX_VALUE;
155             }
156 
157             @Override
158             public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
159                 responseTrigger.submitResponse(unauthorized, responseContentProducer);
160             }
161 
162             @Override
163             public void releaseResources() {
164                 if (responseContentProducer != null) {
165                     responseContentProducer.releaseResources();
166                 }
167             }
168 
169         };
170     }
171 
172 }