View Javadoc

1   /**
2    * This file Copyright (c) 2011-2014 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 info.magnolia.cms.filters.OncePerRequestAbstractMgnlFilter;
37  import info.magnolia.cms.security.auth.callback.HttpClientCallback;
38  
39  import java.io.IOException;
40  import java.util.ArrayList;
41  import java.util.List;
42  
43  import javax.servlet.FilterChain;
44  import javax.servlet.ServletException;
45  import javax.servlet.http.HttpServletRequest;
46  import javax.servlet.http.HttpServletResponse;
47  import javax.servlet.http.HttpServletResponseWrapper;
48  
49  
50  import static info.magnolia.cms.util.ExceptionUtil.rethrow;
51  import static info.magnolia.cms.util.ExceptionUtil.wasCausedBy;
52  import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
53  import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
54  
55  /**
56   * A filter which handles 401, 403 HTTP response codes, as well as {@link javax.jcr.AccessDeniedException}s,
57   * and renders an appropriate "login form" (which can consist of a redirect or anything else just as well).
58   *
59   * A number of {@link HttpClientCallback}s can be configured for this filter, each with a different configuration,
60   * and behavior. The {@link info.magnolia.cms.security.auth.callback.AbstractHttpClientCallback} provides a number
61   * of filtering capabilities (using url, host or voters).
62   *
63   *
64   * This functionality used to live in {@link BaseSecurityFilter}, {@link URISecurityFilter}, as well as {@link ContentSecurityFilter}.
65   * These filters now merely set an HTTP response code or throw an exception, which is handled here.
66   *
67   * @author gjoseph
68   * @version $Revision: $ ($Author: $)
69   */
70  public class SecurityCallbackFilter extends OncePerRequestAbstractMgnlFilter {
71      private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(SecurityCallbackFilter.class);
72  
73      /**
74       * Used to tell the client that he has to login: serve a login page, set http headers or redirect.
75       */
76      private final List<HttpClientCallback> clientCallbacks;
77  
78      public SecurityCallbackFilter() {
79          this.clientCallbacks = new ArrayList<HttpClientCallback>();
80      }
81  
82      @Override
83      public void doFilter(HttpServletRequest request, HttpServletResponse originalResponse, FilterChain chain) throws IOException, ServletException {
84          final StatusSniffingResponseWrapper response = new StatusSniffingResponseWrapper(originalResponse);
85          try {
86              chain.doFilter(request, response);
87              if (needsCallback(response)) {
88                  selectAndHandleCallback(request, response);
89              }
90          } catch (Throwable e) {
91              // an exception was thrown in the filter chain, let's see if it wraps an AccessDeniedException
92              if (wasCausedBy(e, javax.jcr.AccessDeniedException.class)) {
93                  response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
94                  selectAndHandleCallback(request, response);
95              } else {
96                  rethrow(e, IOException.class, ServletException.class);
97              }
98          }
99      }
100 
101     protected boolean needsCallback(StatusSniffingResponseWrapper response) {
102         final int status = response.getStatus();
103         return status == SC_FORBIDDEN || status == SC_UNAUTHORIZED;
104     }
105 
106     protected void selectAndHandleCallback(HttpServletRequest request, StatusSniffingResponseWrapper response) {
107         selectClientCallback(request).handle(request, response);
108     }
109 
110     protected HttpClientCallback selectClientCallback(HttpServletRequest request) {
111         for (HttpClientCallback clientCallback : clientCallbacks) {
112             if (clientCallback.accepts(request)) {
113                 return clientCallback;
114             }
115         }
116         throw new IllegalStateException("No configured callback accepted this request " + request.toString());
117     }
118 
119     // ---- configuration methods
120     public void addClientCallback(HttpClientCallback clientCallback) {
121         this.clientCallbacks.add(clientCallback);
122     }
123 
124     // TODO needs to be public to be seen by c2b!?
125     public List<HttpClientCallback> getClientCallbacks() {
126         return clientCallbacks;
127     }
128 
129     /**
130      * A simple HttpServletResponseWrapper which keeps track of the current http status code.
131      * Everything else is delegated to the parent response, which means calls to sendError or sendRedirect still mean
132      * the response is committed.
133      *
134      * Note: Will become obsolete with Servlet API 3.0 as it defines a publicly available HttpServletResponse#getStatus()
135      */
136     public static class StatusSniffingResponseWrapper extends HttpServletResponseWrapper {
137         private int status = SC_OK;
138 
139         public StatusSniffingResponseWrapper(HttpServletResponse response) {
140             super(response);
141         }
142 
143         public int getStatus() {
144             return status;
145         }
146 
147         @Override
148         public void reset() {
149             super.reset();
150             status = SC_OK;
151         }
152 
153         @Override
154         public void setStatus(int sc) {
155             super.setStatus(sc);
156             this.status = sc;
157         }
158 
159         @Override
160         public void setStatus(int sc, String sm) {
161             super.setStatus(sc, sm);
162             this.status = sc;
163         }
164 
165         @Override
166         public void sendRedirect(String location) throws IOException {
167             super.sendRedirect(location);
168             this.status = SC_MOVED_TEMPORARILY;
169         }
170 
171         @Override
172         public void sendError(int sc) throws IOException {
173             super.sendError(sc);
174             this.status = sc;
175         }
176 
177         @Override
178         public void sendError(int sc, String msg) throws IOException {
179             super.sendError(sc, msg);
180             this.status = sc;
181         }
182     }
183 }