001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.shiro.web.filter.authc;
020
021import org.apache.shiro.authc.AuthenticationToken;
022import org.apache.shiro.codec.Base64;
023import org.apache.shiro.web.util.WebUtils;
024import org.slf4j.Logger;
025import org.slf4j.LoggerFactory;
026
027import javax.servlet.ServletRequest;
028import javax.servlet.ServletResponse;
029import javax.servlet.http.HttpServletRequest;
030import javax.servlet.http.HttpServletResponse;
031import java.util.HashSet;
032import java.util.Locale;
033import java.util.Set;
034
035
036/**
037 * Requires the requesting user to be {@link org.apache.shiro.subject.Subject#isAuthenticated() authenticated} for the
038 * request to continue, and if they're not, requires the user to login via the HTTP Basic protocol-specific challenge.
039 * Upon successful login, they're allowed to continue on to the requested resource/url.
040 * <p/>
041 * This implementation is a 'clean room' Java implementation of Basic HTTP Authentication specification per
042 * <a href="ftp://ftp.isi.edu/in-notes/rfc2617.txt">RFC 2617</a>.
043 * <p/>
044 * Basic authentication functions as follows:
045 * <ol>
046 * <li>A request comes in for a resource that requires authentication.</li>
047 * <li>The server replies with a 401 response status, sets the <code>WWW-Authenticate</code> header, and the contents of a
048 * page informing the user that the incoming resource requires authentication.</li>
049 * <li>Upon receiving this <code>WWW-Authenticate</code> challenge from the server, the client then takes a
050 * username and a password and puts them in the following format:
051 * <p><code>username:password</code></p></li>
052 * <li>This token is then base 64 encoded.</li>
053 * <li>The client then sends another request for the same resource with the following header:<br/>
054 * <p><code>Authorization: Basic <em>Base64_encoded_username_and_password</em></code></p></li>
055 * </ol>
056 * The {@link #onAccessDenied(javax.servlet.ServletRequest, javax.servlet.ServletResponse)} method will
057 * only be called if the subject making the request is not
058 * {@link org.apache.shiro.subject.Subject#isAuthenticated() authenticated}
059 *
060 * @see <a href="https://tools.ietf.org/html/rfc2617">RFC 2617</a>
061 * @see <a href="http://en.wikipedia.org/wiki/Basic_access_authentication">Basic Access Authentication</a>
062 * @since 0.9
063 */
064public class BasicHttpAuthenticationFilter extends HttpAuthenticationFilter {
065
066    /**
067     * This class's private logger.
068     */
069    private static final Logger log = LoggerFactory.getLogger(BasicHttpAuthenticationFilter.class);
070
071
072    public BasicHttpAuthenticationFilter() {
073        setAuthcScheme(HttpServletRequest.BASIC_AUTH);
074        setAuthzScheme(HttpServletRequest.BASIC_AUTH);
075    }
076
077    /**
078     * Creates an AuthenticationToken for use during login attempt with the provided credentials in the http header.
079     * <p/>
080     * This implementation:
081     * <ol><li>acquires the username and password based on the request's
082     * {@link #getAuthzHeader(javax.servlet.ServletRequest) authorization header} via the
083     * {@link #getPrincipalsAndCredentials(String, javax.servlet.ServletRequest) getPrincipalsAndCredentials} method</li>
084     * <li>The return value of that method is converted to an <code>AuthenticationToken</code> via the
085     * {@link #createToken(String, String, javax.servlet.ServletRequest, javax.servlet.ServletResponse) createToken} method</li>
086     * <li>The created <code>AuthenticationToken</code> is returned.</li>
087     * </ol>
088     *
089     * @param request  incoming ServletRequest
090     * @param response outgoing ServletResponse
091     * @return the AuthenticationToken used to execute the login attempt
092     */
093    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
094        String authorizationHeader = getAuthzHeader(request);
095        if (authorizationHeader == null || authorizationHeader.length() == 0) {
096            // Create an empty authentication token since there is no
097            // Authorization header.
098            return createToken("", "", request, response);
099        }
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}