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     */
019    package org.tynamo.security.shiro.authz;
020    
021    import java.io.IOException;
022    
023    import javax.servlet.ServletRequest;
024    import javax.servlet.ServletResponse;
025    import javax.servlet.http.HttpServletResponse;
026    
027    import org.apache.shiro.subject.Subject;
028    import org.apache.shiro.util.StringUtils;
029    import org.apache.shiro.web.util.WebUtils;
030    import org.tynamo.security.shiro.AccessControlFilter;
031    
032    /**
033     * Superclass for authorization-related filters.  If an request is unauthorized, response handling is delegated to the
034     * {@link #onAccessDenied(javax.servlet.ServletRequest, javax.servlet.ServletResponse) onAccessDenied} method, which
035     * provides reasonable handling for most applications.
036     *
037     * @see #onAccessDenied(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
038     * @since 0.4.0
039     */
040    public abstract class AuthorizationFilter extends AccessControlFilter {
041    
042        /**
043         * The URL to which users should be redirected if they are denied access to an underlying path or resource,
044         * {@code null} by default which will issue a raw {@link HttpServletResponse#SC_UNAUTHORIZED} response
045         * (401 Unauthorized).
046         */
047        private String unauthorizedUrl;
048    
049        /**
050         * Returns the URL to which users should be redirected if they are denied access to an underlying path or resource,
051         * or {@code null} if a raw {@link HttpServletResponse#SC_UNAUTHORIZED} response should be issued (401 Unauthorized).
052         * <p/>
053         * The default is {@code null}, ensuring default web server behavior.  Override this default by calling the
054         * {@link #setUnauthorizedUrl(String) setUnauthorizedUrl} method with a meaningful path within your application
055         * if you would like to show the user a 'nice' page in the event of unauthorized access.
056         *
057         * @return the URL to which users should be redirected if they are denied access to an underlying path or resource,
058         *         or {@code null} if a raw {@link HttpServletResponse#SC_UNAUTHORIZED} response should be issued (401 Unauthorized).
059         */
060        public String getUnauthorizedUrl() {
061            return unauthorizedUrl;
062        }
063    
064        /**
065         * Sets the URL to which users should be redirected if they are denied access to an underlying path or resource.
066         * <p/>
067         * If the value is {@code null} a raw {@link HttpServletResponse#SC_UNAUTHORIZED} response will
068         * be issued (401 Unauthorized), retaining default web server behavior.
069         * <p/>
070         * Unless overridden by calling this method, the default value is {@code null}.  If desired, you can specify a
071         * meaningful path within your application if you would like to show the user a 'nice' page in the event of
072         * unauthorized access.
073         *
074         * @param unauthorizedUrl the URL to which users should be redirected if they are denied access to an underlying
075         *                        path or resource, or {@code null} to a ensure raw {@link HttpServletResponse#SC_UNAUTHORIZED} response is
076         *                        issued (401 Unauthorized).
077         */
078        public void setUnauthorizedUrl(String unauthorizedUrl) {
079            this.unauthorizedUrl = unauthorizedUrl;
080        }
081    
082        /**
083         * Handles the response when access has been denied.  It behaves as follows:
084         * <ul>
085         * <li>If the {@code Subject} is unknown<sup><a href="#known">[1]</a></sup>:
086         * <ol><li>The incoming request will be saved and they will be redirected to the login page for authentication
087         * (via the {@link #saveRequestAndRedirectToLogin(javax.servlet.ServletRequest, javax.servlet.ServletResponse)}
088         * method).</li>
089         * <li>Once successfully authenticated, they will be redirected back to the originally attempted page.</li></ol>
090         * </li>
091         * <li>If the Subject is known:</li>
092         * <ol>
093         * <li>The HTTP {@link HttpServletResponse#SC_UNAUTHORIZED} header will be set (401 Unauthorized)</li>
094         * <li>If the {@link #getUnauthorizedUrl() unauthorizedUrl} has been configured, a redirect will be issued to that
095         * URL.  Otherwise the 401 response is rendered normally</li>
096         * </ul>
097         * <code><a name="known">[1]</a></code>: A {@code Subject} is 'known' when
098         * <code>subject.{@link org.apache.shiro.subject.Subject#getPrincipal() getPrincipal()}</code> is not {@code null},
099         * which implicitly means that the subject is either currently authenticated or they have been remembered via
100         * 'remember me' services.
101         *
102         * @param request  the incoming <code>ServletRequest</code>
103         * @param response the outgoing <code>ServletResponse</code>
104         * @return {@code false} always for this implementation.
105         * @throws IOException if there is any servlet error.
106         */
107        protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
108    
109            Subject subject = getSubject(request, response);
110            // If the subject isn't identified, redirect to login URL
111            if (subject.getPrincipal() == null) {
112                saveRequestAndRedirectToLogin(request, response);
113            } else {
114                // If subject is known but not authorized, redirect to the unauthorized URL if there is one
115                // If no unauthorized URL is specified, just return an unauthorized HTTP status code
116                String unauthorizedUrl = getUnauthorizedUrl();
117                //SHIRO-142 - ensure that redirect _or_ error code occurs - both cannot happen due to response commit:
118                if (StringUtils.hasText(unauthorizedUrl)) {
119                    WebUtils.issueRedirect(request, response, unauthorizedUrl);
120                } else {
121                    WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
122                }
123            }
124            return false;
125        }
126    
127    }