View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.shiro.web.filter.authc;
20  
21  import org.apache.shiro.authc.AuthenticationToken;
22  import org.apache.shiro.codec.Base64;
23  import org.apache.shiro.web.util.WebUtils;
24  import org.slf4j.Logger;
25  import org.slf4j.LoggerFactory;
26  
27  import javax.servlet.ServletRequest;
28  import javax.servlet.ServletResponse;
29  import javax.servlet.http.HttpServletRequest;
30  import javax.servlet.http.HttpServletResponse;
31  import java.util.HashSet;
32  import java.util.Locale;
33  import java.util.Set;
34  
35  
36  /**
37   * Requires the requesting user to be {@link org.apache.shiro.subject.Subject#isAuthenticated() authenticated} for the
38   * request to continue, and if they're not, requires the user to login via the HTTP Basic protocol-specific challenge.
39   * Upon successful login, they're allowed to continue on to the requested resource/url.
40   * <p/>
41   * This implementation is a 'clean room' Java implementation of Basic HTTP Authentication specification per
42   * <a href="ftp://ftp.isi.edu/in-notes/rfc2617.txt">RFC 2617</a>.
43   * <p/>
44   * Basic authentication functions as follows:
45   * <ol>
46   * <li>A request comes in for a resource that requires authentication.</li>
47   * <li>The server replies with a 401 response status, sets the <code>WWW-Authenticate</code> header, and the contents of a
48   * page informing the user that the incoming resource requires authentication.</li>
49   * <li>Upon receiving this <code>WWW-Authenticate</code> challenge from the server, the client then takes a
50   * username and a password and puts them in the following format:
51   * <p><code>username:password</code></p></li>
52   * <li>This token is then base 64 encoded.</li>
53   * <li>The client then sends another request for the same resource with the following header:<br/>
54   * <p><code>Authorization: Basic <em>Base64_encoded_username_and_password</em></code></p></li>
55   * </ol>
56   * The {@link #onAccessDenied(javax.servlet.ServletRequest, javax.servlet.ServletResponse)} method will
57   * only be called if the subject making the request is not
58   * {@link org.apache.shiro.subject.Subject#isAuthenticated() authenticated}
59   *
60   * @see <a href="https://tools.ietf.org/html/rfc2617">RFC 2617</a>
61   * @see <a href="http://en.wikipedia.org/wiki/Basic_access_authentication">Basic Access Authentication</a>
62   * @since 0.9
63   */
64  public class BasicHttpAuthenticationFilter extends HttpAuthenticationFilter {
65  
66      /**
67       * This class's private logger.
68       */
69      private static final Logger log = LoggerFactory.getLogger(BasicHttpAuthenticationFilter.class);
70  
71  
72      public BasicHttpAuthenticationFilter() {
73          setAuthcScheme(HttpServletRequest.BASIC_AUTH);
74          setAuthzScheme(HttpServletRequest.BASIC_AUTH);
75      }
76  
77      /**
78       * Creates an AuthenticationToken for use during login attempt with the provided credentials in the http header.
79       * <p/>
80       * This implementation:
81       * <ol><li>acquires the username and password based on the request's
82       * {@link #getAuthzHeader(javax.servlet.ServletRequest) authorization header} via the
83       * {@link #getPrincipalsAndCredentials(String, javax.servlet.ServletRequest) getPrincipalsAndCredentials} method</li>
84       * <li>The return value of that method is converted to an <code>AuthenticationToken</code> via the
85       * {@link #createToken(String, String, javax.servlet.ServletRequest, javax.servlet.ServletResponse) createToken} method</li>
86       * <li>The created <code>AuthenticationToken</code> is returned.</li>
87       * </ol>
88       *
89       * @param request  incoming ServletRequest
90       * @param response outgoing ServletResponse
91       * @return the AuthenticationToken used to execute the login attempt
92       */
93      protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
94          String authorizationHeader = getAuthzHeader(request);
95          if (authorizationHeader == null || authorizationHeader.length() == 0) {
96              // Create an empty authentication token since there is no
97              // Authorization header.
98              return createToken("", "", request, response);
99          }
100 
101         log.debug("Attempting to execute login with auth header");
102 
103         String[] prinCred = getPrincipalsAndCredentials(authorizationHeader, request);
104         if (prinCred == null || prinCred.length < 2) {
105             // Create an authentication token with an empty password,
106             // since one hasn't been provided in the request.
107             String username = prinCred == null || prinCred.length == 0 ? "" : prinCred[0];
108             return createToken(username, "", request, response);
109         }
110 
111         String username = prinCred[0];
112         String password = prinCred[1];
113 
114         return createToken(username, password, request, response);
115     }
116 
117     /**
118      * Returns the username and password pair based on the specified <code>encoded</code> String obtained from
119      * the request's authorization header.
120      * <p/>
121      * Per RFC 2617, the default implementation first Base64 decodes the string and then splits the resulting decoded
122      * string into two based on the ":" character.  That is:
123      * <p/>
124      * <code>String decoded = Base64.decodeToString(encoded);<br/>
125      * return decoded.split(":");</code>
126      *
127      * @param scheme  the {@link #getAuthcScheme() authcScheme} found in the request
128      *                {@link #getAuthzHeader(javax.servlet.ServletRequest) authzHeader}.  It is ignored by this implementation,
129      *                but available to overriding implementations should they find it useful.
130      * @param encoded the Base64-encoded username:password value found after the scheme in the header
131      * @return the username (index 0)/password (index 1) pair obtained from the encoded header data.
132      */
133     protected String[] getPrincipalsAndCredentials(String scheme, String encoded) {
134         String decoded = Base64.decodeToString(encoded);
135         return decoded.split(":", 2);
136     }
137 }