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  
28  package org.apache.hc.client5.testing.classic;
29  
30  import java.io.IOException;
31  import java.nio.charset.StandardCharsets;
32  import java.util.ArrayList;
33  import java.util.List;
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.ClassicHttpRequest;
40  import org.apache.hc.core5.http.ClassicHttpResponse;
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.HttpStatus;
45  import org.apache.hc.core5.http.NameValuePair;
46  import org.apache.hc.core5.http.io.HttpServerRequestHandler;
47  import org.apache.hc.core5.http.io.entity.EntityUtils;
48  import org.apache.hc.core5.http.io.entity.StringEntity;
49  import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
50  import org.apache.hc.core5.http.message.BasicNameValuePair;
51  import org.apache.hc.core5.http.protocol.HttpContext;
52  import org.apache.hc.core5.net.URIAuthority;
53  import org.apache.hc.core5.util.Args;
54  
55  public class AuthenticatingDecorator implements HttpServerRequestHandler {
56  
57      private final HttpServerRequestHandler requestHandler;
58      private final AuthenticationHandler<String> authenticationHandler;
59      private final Authenticator authenticator;
60  
61      /**
62       * @since 5.3
63       */
64      public AuthenticatingDecorator(final HttpServerRequestHandler requestHandler,
65                                     final AuthenticationHandler<String> authenticationHandler,
66                                     final Authenticator authenticator) {
67          this.requestHandler = Args.notNull(requestHandler, "Request handler");
68          this.authenticationHandler = Args.notNull(authenticationHandler, "Authentication handler");
69          this.authenticator = Args.notNull(authenticator, "Authenticator");
70      }
71  
72      public AuthenticatingDecorator(final HttpServerRequestHandler requestHandler,
73                                     final Authenticator authenticator) {
74          this(requestHandler, new BasicAuthenticationHandler(StandardCharsets.US_ASCII), authenticator);
75      }
76  
77      protected void customizeUnauthorizedResponse(final ClassicHttpResponse unauthorized) {
78      }
79  
80      @Override
81      public void handle(
82              final ClassicHttpRequest request,
83              final ResponseTrigger responseTrigger,
84              final HttpContext context) throws HttpException, IOException {
85          final Header h = request.getFirstHeader(HttpHeaders.AUTHORIZATION);
86          final String challengeResponse = h != null ? authenticationHandler.extractAuthToken(h.getValue()) : null;
87  
88          final URIAuthority authority = request.getAuthority();
89          final String requestUri = request.getRequestUri();
90  
91          final AuthResult authResult = authenticator.perform(authority, requestUri, challengeResponse);
92          final Header expect = request.getFirstHeader(HttpHeaders.EXPECT);
93          final boolean expectContinue = expect != null && "100-continue".equalsIgnoreCase(expect.getValue());
94  
95          if (authResult.isSuccess()) {
96              if (expectContinue) {
97                  responseTrigger.sendInformation(new BasicClassicHttpResponse(HttpStatus.SC_CONTINUE));
98              }
99              requestHandler.handle(request, responseTrigger, context);
100         } else {
101             final ClassicHttpResponse unauthorized = new BasicClassicHttpResponse(HttpStatus.SC_UNAUTHORIZED);
102             final List<NameValuePair> challengeParams = new ArrayList<>();
103             final String realm = authenticator.getRealm(authority, requestUri);
104             if (realm != null) {
105                 challengeParams.add(new BasicNameValuePair("realm", realm));
106             }
107             if (authResult.hasParams()) {
108                 challengeParams.addAll(authResult.getParams());
109             }
110             final String challenge = authenticationHandler.challenge(challengeParams);
111             unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, challenge);
112             customizeUnauthorizedResponse(unauthorized);
113             if (unauthorized.getEntity() == null) {
114                 unauthorized.setEntity(new StringEntity("Unauthorized"));
115             }
116             if (expectContinue || request.getEntity() == null) {
117                 // Respond immediately
118                 responseTrigger.submitResponse(unauthorized);
119                 // Consume request body later
120                 EntityUtils.consume(request.getEntity());
121             } else {
122                 // Consume request body first
123                 EntityUtils.consume(request.getEntity());
124                 // Respond later
125                 responseTrigger.submitResponse(unauthorized);
126             }
127         }
128     }
129 
130 }