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