View Javadoc
1   /**
2    * This file Copyright (c) 2011-2016 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.cms.security;
35  
36  import static info.magnolia.cms.util.ExceptionUtil.*;
37  import static javax.servlet.http.HttpServletResponse.*;
38  
39  import info.magnolia.cms.filters.OncePerRequestAbstractMgnlFilter;
40  import info.magnolia.cms.security.auth.callback.HttpClientCallback;
41  
42  import java.io.IOException;
43  import java.util.ArrayList;
44  import java.util.List;
45  
46  import javax.servlet.FilterChain;
47  import javax.servlet.ServletException;
48  import javax.servlet.http.HttpServletRequest;
49  import javax.servlet.http.HttpServletResponse;
50  import javax.servlet.http.HttpServletResponseWrapper;
51  
52  /**
53   * A filter which handles 401, 403 HTTP response codes, as well as {@link javax.jcr.AccessDeniedException}s,
54   * and renders an appropriate "login form" (which can consist of a redirect or anything else just as well).
55   *
56   * A number of {@link HttpClientCallback}s can be configured for this filter, each with a different configuration,
57   * and behavior. The {@link info.magnolia.cms.security.auth.callback.AbstractHttpClientCallback} provides a number
58   * of filtering capabilities (using url, host or voters).
59   *
60   *
61   * This functionality used to live in {@link BaseSecurityFilter}, {@link URISecurityFilter}, as well as {@link ContentSecurityFilter}.
62   * These filters now merely set an HTTP response code or throw an exception, which is handled here.
63   */
64  public class SecurityCallbackFilter extends OncePerRequestAbstractMgnlFilter {
65  
66      /**
67       * Used to tell the client that he has to login: serve a login page, set http headers or redirect.
68       */
69      private final List<HttpClientCallback> clientCallbacks;
70  
71      public SecurityCallbackFilter() {
72          this.clientCallbacks = new ArrayList<>();
73      }
74  
75      @Override
76      public void doFilter(HttpServletRequest request, HttpServletResponse originalResponse, FilterChain chain) throws IOException, ServletException {
77          final StatusSniffingResponseWrapper response = new StatusSniffingResponseWrapper(originalResponse);
78          try {
79              chain.doFilter(request, response);
80              if (needsCallback(response)) {
81                  selectAndHandleCallback(request, response);
82              }
83          } catch (Throwable e) {
84              // an exception was thrown in the filter chain, let's see if it wraps an AccessDeniedException
85              if (wasCausedBy(e, javax.jcr.AccessDeniedException.class)) {
86                  response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
87                  selectAndHandleCallback(request, response);
88              } else {
89                  rethrow(e, IOException.class, ServletException.class);
90              }
91          }
92      }
93  
94      protected boolean needsCallback(StatusSniffingResponseWrapper response) {
95          final int status = response.getStatus();
96          return status == SC_FORBIDDEN || status == SC_UNAUTHORIZED;
97      }
98  
99      protected void selectAndHandleCallback(HttpServletRequest request, StatusSniffingResponseWrapper response) {
100         selectClientCallback(request).handle(request, response);
101     }
102 
103     protected HttpClientCallback selectClientCallback(HttpServletRequest request) {
104         for (HttpClientCallback clientCallback : clientCallbacks) {
105             if (clientCallback.accepts(request)) {
106                 return clientCallback;
107             }
108         }
109         throw new IllegalStateException("No configured callback accepted this request " + request.toString());
110     }
111 
112     // ---- configuration methods
113     public void addClientCallback(HttpClientCallback clientCallback) {
114         this.clientCallbacks.add(clientCallback);
115     }
116 
117     public void setClientCallbacks(List<HttpClientCallback> clientCallbacks) {
118         this.clientCallbacks.addAll(clientCallbacks);
119     }
120 
121     // TODO needs to be public to be seen by c2b!?
122     public List<HttpClientCallback> getClientCallbacks() {
123         return clientCallbacks;
124     }
125 
126     /**
127      * A simple HttpServletResponseWrapper which keeps track of the current http status code.
128      * Everything else is delegated to the parent response, which means calls to sendError or sendRedirect still mean
129      * the response is committed.
130      *
131      * Note: Will become obsolete with Servlet API 3.0 as it defines a publicly available HttpServletResponse#getStatus()
132      */
133     public static class StatusSniffingResponseWrapper extends HttpServletResponseWrapper {
134         private int status = SC_OK;
135 
136         public StatusSniffingResponseWrapper(HttpServletResponse response) {
137             super(response);
138         }
139 
140         public int getStatus() {
141             return status;
142         }
143 
144         @Override
145         public void reset() {
146             super.reset();
147             status = SC_OK;
148         }
149 
150         @Override
151         public void setStatus(int sc) {
152             super.setStatus(sc);
153             this.status = sc;
154         }
155 
156         @Override
157         public void setStatus(int sc, String sm) {
158             super.setStatus(sc, sm);
159             this.status = sc;
160         }
161 
162         @Override
163         public void sendRedirect(String location) throws IOException {
164             super.sendRedirect(location);
165             this.status = SC_MOVED_TEMPORARILY;
166         }
167 
168         @Override
169         public void sendError(int sc) throws IOException {
170             super.sendError(sc);
171             this.status = sc;
172         }
173 
174         @Override
175         public void sendError(int sc, String msg) throws IOException {
176             super.sendError(sc, msg);
177             this.status = sc;
178         }
179     }
180 }