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.lang.codec.Base64;
23  import org.slf4j.Logger;
24  import org.slf4j.LoggerFactory;
25  
26  import javax.servlet.ServletRequest;
27  import javax.servlet.ServletResponse;
28  import javax.servlet.http.HttpServletRequest;
29  
30  
31  /**
32   * Requires the requesting user to be {@link org.apache.shiro.subject.Subject#isAuthenticated() authenticated} for the
33   * request to continue, and if they're not, requires the user to login via the HTTP Basic protocol-specific challenge.
34   * Upon successful login, they're allowed to continue on to the requested resource/url.
35   * <p/>
36   * This implementation is a 'clean room' Java implementation of Basic HTTP Authentication specification per
37   * <a href="ftp://ftp.isi.edu/in-notes/rfc2617.txt">RFC 2617</a>.
38   * <p/>
39   * Basic authentication functions as follows:
40   * <ol>
41   * <li>A request comes in for a resource that requires authentication.</li>
42   * <li>The server replies with a 401 response status, sets the <code>WWW-Authenticate</code> header, and the contents of a
43   * page informing the user that the incoming resource requires authentication.</li>
44   * <li>Upon receiving this <code>WWW-Authenticate</code> challenge from the server, the client then takes a
45   * username and a password and puts them in the following format:
46   * <p><code>username:password</code></p></li>
47   * <li>This token is then base 64 encoded.</li>
48   * <li>The client then sends another request for the same resource with the following header:<br/>
49   * <p><code>Authorization: Basic <em>Base64_encoded_username_and_password</em></code></p></li>
50   * </ol>
51   * The {@link #onAccessDenied(javax.servlet.ServletRequest, javax.servlet.ServletResponse)} method will
52   * only be called if the subject making the request is not
53   * {@link org.apache.shiro.subject.Subject#isAuthenticated() authenticated}
54   *
55   * @see <a href="https://tools.ietf.org/html/rfc2617">RFC 2617</a>
56   * @see <a href="http://en.wikipedia.org/wiki/Basic_access_authentication">Basic Access Authentication</a>
57   * @since 0.9
58   */
59  public class BasicHttpAuthenticationFilter extends HttpAuthenticationFilter {
60  
61      /**
62       * This class's private logger.
63       */
64      private static final Logger LOGGER = LoggerFactory.getLogger(BasicHttpAuthenticationFilter.class);
65  
66  
67      public BasicHttpAuthenticationFilter() {
68          setAuthcScheme(HttpServletRequest.BASIC_AUTH);
69          setAuthzScheme(HttpServletRequest.BASIC_AUTH);
70      }
71  
72      /**
73       * Creates an AuthenticationToken for use during login attempt with the provided credentials in the http header.
74       * <p/>
75       * This implementation:
76       * <ol><li>acquires the username and password based on the request's
77       * {@link #getAuthzHeader(javax.servlet.ServletRequest) authorization header} via the
78       * {@link #getPrincipalsAndCredentials(String, javax.servlet.ServletRequest) getPrincipalsAndCredentials} method</li>
79       * <li>The return value of that method is converted to an <code>AuthenticationToken</code> via the
80       * {@link #createToken(String, String, javax.servlet.ServletRequest, javax.servlet.ServletResponse) createToken} method</li>
81       * <li>The created <code>AuthenticationToken</code> is returned.</li>
82       * </ol>
83       *
84       * @param request  incoming ServletRequest
85       * @param response outgoing ServletResponse (never used)
86       * @return the AuthenticationToken used to execute the login attempt
87       */
88      @Override
89      protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
90          String authorizationHeader = getAuthzHeader(request);
91          if (authorizationHeader == null || authorizationHeader.length() == 0) {
92              // Create an empty authentication token since there is no
93              // Authorization header.
94              return createToken("", "", request, response);
95          }
96  
97          LOGGER.debug("Attempting to execute login with auth header");
98  
99          String[] prinCred = getPrincipalsAndCredentials(authorizationHeader, request);
100         if (prinCred == null || prinCred.length < 2) {
101             // Create an authentication token with an empty password,
102             // since one hasn't been provided in the request.
103             String username = prinCred == null || prinCred.length == 0 ? "" : prinCred[0];
104             return createToken(username, "", request, response);
105         }
106 
107         String username = prinCred[0];
108         String password = prinCred[1];
109 
110         return createToken(username, password, request, response);
111     }
112 
113     /**
114      * Returns the username and password pair based on the specified <code>encoded</code> String obtained from
115      * the request's authorization header.
116      * <p/>
117      * Per RFC 2617, the default implementation first Base64 decodes the string and then splits the resulting decoded
118      * string into two based on the ":" character.  That is:
119      * <p/>
120      * <code>String decoded = Base64.decodeToString(encoded);<br/>
121      * return decoded.split(":");</code>
122      *
123      * @param scheme  the {@link #getAuthcScheme() authcScheme} found in the request
124      *                {@link #getAuthzHeader(javax.servlet.ServletRequest) authzHeader}.  It is ignored by this implementation,
125      *                but available to overriding implementations should they find it useful.
126      * @param encoded the Base64-encoded username:password value found after the scheme in the header
127      * @return the username (index 0)/password (index 1) pair obtained from the encoded header data.
128      */
129     @Override
130     protected String[] getPrincipalsAndCredentials(String scheme, String encoded) {
131         String decoded = Base64.decodeToString(encoded);
132         return decoded.split(":", 2);
133     }
134 }