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 final Base64 base64codec;
57      /** Whether the basic authentication process is complete */
58      private boolean complete;
59  
60      /**
61       * @since 4.3
62       */
63      public BasicScheme(final Charset credentialsCharset) {
64          super(credentialsCharset);
65          this.base64codec = new Base64(0);
66          this.complete = false;
67      }
68  
69      /**
70       * Creates an instance of <tt>BasicScheme</tt> 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          this.base64codec = new Base64(0);
81      }
82  
83      public BasicScheme() {
84          this(Consts.ASCII);
85      }
86  
87      /**
88       * Returns textual designation of the basic authentication scheme.
89       *
90       * @return <code>basic</code>
91       */
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 <tt>true</tt> if Basic authorization has been processed,
115      *   <tt>false</tt> otherwise.
116      */
117     public boolean isComplete() {
118         return this.complete;
119     }
120 
121     /**
122      * Returns <tt>false</tt>. Basic authentication scheme is request based.
123      *
124      * @return <tt>false</tt>.
125      */
126     public boolean isConnectionBased() {
127         return false;
128     }
129 
130     /**
131      * @deprecated (4.2) Use {@link org.apache.http.auth.ContextAwareAuthScheme#authenticate(
132      *   Credentials, HttpRequest, org.apache.http.protocol.HttpContext)}
133      */
134     @Deprecated
135     public Header authenticate(
136             final Credentials credentials, final HttpRequest request) throws AuthenticationException {
137         return authenticate(credentials, request, new BasicHttpContext());
138     }
139 
140     /**
141      * Produces basic authorization header for the given set of {@link Credentials}.
142      *
143      * @param credentials The set of credentials to be used for authentication
144      * @param request The request being authenticated
145      * @throws org.apache.http.auth.InvalidCredentialsException if authentication
146      *   credentials are not valid or not applicable for this authentication scheme
147      * @throws AuthenticationException if authorization string cannot
148      *   be generated due to an authentication failure
149      *
150      * @return a basic authorization string
151      */
152     @Override
153     public Header authenticate(
154             final Credentials credentials,
155             final HttpRequest request,
156             final HttpContext context) throws AuthenticationException {
157 
158         Args.notNull(credentials, "Credentials");
159         Args.notNull(request, "HTTP request");
160         final StringBuilder tmp = new StringBuilder();
161         tmp.append(credentials.getUserPrincipal().getName());
162         tmp.append(":");
163         tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());
164 
165         final byte[] base64password = base64codec.encode(
166                 EncodingUtils.getBytes(tmp.toString(), getCredentialsCharset(request)));
167 
168         final CharArrayBuffer buffer = new CharArrayBuffer(32);
169         if (isProxy()) {
170             buffer.append(AUTH.PROXY_AUTH_RESP);
171         } else {
172             buffer.append(AUTH.WWW_AUTH_RESP);
173         }
174         buffer.append(": Basic ");
175         buffer.append(base64password, 0, base64password.length);
176 
177         return new BufferedHeader(buffer);
178     }
179 
180     /**
181      * Returns a basic <tt>Authorization</tt> header value for the given
182      * {@link Credentials} and charset.
183      *
184      * @param credentials The credentials to encode.
185      * @param charset The charset to use for encoding the credentials
186      *
187      * @return a basic authorization header
188      *
189      * @deprecated (4.3) use {@link #authenticate(Credentials, HttpRequest, HttpContext)}.
190      */
191     @Deprecated
192     public static Header authenticate(
193             final Credentials credentials,
194             final String charset,
195             final boolean proxy) {
196         Args.notNull(credentials, "Credentials");
197         Args.notNull(charset, "charset");
198 
199         final StringBuilder tmp = new StringBuilder();
200         tmp.append(credentials.getUserPrincipal().getName());
201         tmp.append(":");
202         tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());
203 
204         final byte[] base64password = Base64.encodeBase64(
205                 EncodingUtils.getBytes(tmp.toString(), charset), false);
206 
207         final CharArrayBuffer buffer = new CharArrayBuffer(32);
208         if (proxy) {
209             buffer.append(AUTH.PROXY_AUTH_RESP);
210         } else {
211             buffer.append(AUTH.WWW_AUTH_RESP);
212         }
213         buffer.append(": Basic ");
214         buffer.append(base64password, 0, base64password.length);
215 
216         return new BufferedHeader(buffer);
217     }
218 
219 }