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.http.impl.auth;
28  
29  import java.nio.charset.Charset;
30  
31  import org.apache.commons.codec.binary.Base64;
32  import org.apache.http.Consts;
33  import org.apache.http.Header;
34  import org.apache.http.HttpRequest;
35  import org.apache.http.annotation.NotThreadSafe;
36  import org.apache.http.auth.AUTH;
37  import org.apache.http.auth.AuthenticationException;
38  import org.apache.http.auth.ChallengeState;
39  import org.apache.http.auth.Credentials;
40  import org.apache.http.auth.MalformedChallengeException;
41  import org.apache.http.message.BufferedHeader;
42  import org.apache.http.protocol.BasicHttpContext;
43  import org.apache.http.protocol.HttpContext;
44  import org.apache.http.util.Args;
45  import org.apache.http.util.CharArrayBuffer;
46  import org.apache.http.util.EncodingUtils;
47  
48  /**
49   * Basic authentication scheme as defined in RFC 2617.
50   *
51   * @since 4.0
52   */
53  @NotThreadSafe
54  public class BasicScheme extends RFC2617Scheme {
55  
56      private static final long serialVersionUID = -1931571557597830536L;
57  
58      /** Whether the basic authentication process is complete */
59      private boolean complete;
60  
61      /**
62       * @since 4.3
63       */
64      public BasicScheme(final Charset credentialsCharset) {
65          super(credentialsCharset);
66          this.complete = false;
67      }
68  
69      /**
70       * Creates an instance of {@code BasicScheme} with the given challenge
71       * state.
72       *
73       * @since 4.2
74       *
75       * @deprecated (4.3) do not use.
76       */
77      @Deprecated
78      public BasicScheme(final ChallengeState challengeState) {
79          super(challengeState);
80      }
81  
82      public BasicScheme() {
83          this(Consts.ASCII);
84      }
85  
86      /**
87       * Returns textual designation of the basic authentication scheme.
88       *
89       * @return <code>basic</code>
90       */
91      @Override
92      public String getSchemeName() {
93          return "basic";
94      }
95  
96      /**
97       * Processes the Basic challenge.
98       *
99       * @param header the challenge header
100      *
101      * @throws MalformedChallengeException is thrown if the authentication challenge
102      * is malformed
103      */
104     @Override
105     public void processChallenge(
106             final Header header) throws MalformedChallengeException {
107         super.processChallenge(header);
108         this.complete = true;
109     }
110 
111     /**
112      * Tests if the Basic authentication process has been completed.
113      *
114      * @return {@code true} if Basic authorization has been processed,
115      *   {@code false} otherwise.
116      */
117     @Override
118     public boolean isComplete() {
119         return this.complete;
120     }
121 
122     /**
123      * Returns {@code false}. Basic authentication scheme is request based.
124      *
125      * @return {@code false}.
126      */
127     @Override
128     public boolean isConnectionBased() {
129         return false;
130     }
131 
132     /**
133      * @deprecated (4.2) Use {@link org.apache.http.auth.ContextAwareAuthScheme#authenticate(
134      *   Credentials, HttpRequest, org.apache.http.protocol.HttpContext)}
135      */
136     @Override
137     @Deprecated
138     public Header authenticate(
139             final Credentials credentials, final HttpRequest request) throws AuthenticationException {
140         return authenticate(credentials, request, new BasicHttpContext());
141     }
142 
143     /**
144      * Produces basic authorization header for the given set of {@link Credentials}.
145      *
146      * @param credentials The set of credentials to be used for authentication
147      * @param request The request being authenticated
148      * @throws org.apache.http.auth.InvalidCredentialsException if authentication
149      *   credentials are not valid or not applicable for this authentication scheme
150      * @throws AuthenticationException if authorization string cannot
151      *   be generated due to an authentication failure
152      *
153      * @return a basic authorization string
154      */
155     @Override
156     public Header authenticate(
157             final Credentials credentials,
158             final HttpRequest request,
159             final HttpContext context) throws AuthenticationException {
160 
161         Args.notNull(credentials, "Credentials");
162         Args.notNull(request, "HTTP request");
163         final StringBuilder tmp = new StringBuilder();
164         tmp.append(credentials.getUserPrincipal().getName());
165         tmp.append(":");
166         tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());
167 
168         final Base64 base64codec = new Base64(0);
169         final byte[] base64password = base64codec.encode(
170                 EncodingUtils.getBytes(tmp.toString(), getCredentialsCharset(request)));
171 
172         final CharArrayBuffer buffer = new CharArrayBuffer(32);
173         if (isProxy()) {
174             buffer.append(AUTH.PROXY_AUTH_RESP);
175         } else {
176             buffer.append(AUTH.WWW_AUTH_RESP);
177         }
178         buffer.append(": Basic ");
179         buffer.append(base64password, 0, base64password.length);
180 
181         return new BufferedHeader(buffer);
182     }
183 
184     /**
185      * Returns a basic {@code Authorization} header value for the given
186      * {@link Credentials} and charset.
187      *
188      * @param credentials The credentials to encode.
189      * @param charset The charset to use for encoding the credentials
190      *
191      * @return a basic authorization header
192      *
193      * @deprecated (4.3) use {@link #authenticate(Credentials, HttpRequest, HttpContext)}.
194      */
195     @Deprecated
196     public static Header authenticate(
197             final Credentials credentials,
198             final String charset,
199             final boolean proxy) {
200         Args.notNull(credentials, "Credentials");
201         Args.notNull(charset, "charset");
202 
203         final StringBuilder tmp = new StringBuilder();
204         tmp.append(credentials.getUserPrincipal().getName());
205         tmp.append(":");
206         tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());
207 
208         final byte[] base64password = Base64.encodeBase64(
209                 EncodingUtils.getBytes(tmp.toString(), charset), false);
210 
211         final CharArrayBuffer buffer = new CharArrayBuffer(32);
212         if (proxy) {
213             buffer.append(AUTH.PROXY_AUTH_RESP);
214         } else {
215             buffer.append(AUTH.WWW_AUTH_RESP);
216         }
217         buffer.append(": Basic ");
218         buffer.append(base64password, 0, base64password.length);
219 
220         return new BufferedHeader(buffer);
221     }
222 
223     @Override
224     public String toString() {
225         final StringBuilder builder = new StringBuilder();
226         builder.append("BASIC [complete=").append(complete)
227                 .append("]");
228         return builder.toString();
229     }
230 }