View Javadoc
1   /**
2    * This file Copyright (c) 2011-2015 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  public class SecurityCallbackFilter extends OncePerRequestAbstractMgnlFilter {
68      private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(SecurityCallbackFilter.class);
69  
70      /**
71       * Used to tell the client that he has to login: serve a login page, set http headers or redirect.
72       */
73      private final List<HttpClientCallback> clientCallbacks;
74  
75      public SecurityCallbackFilter() {
76          this.clientCallbacks = new ArrayList<HttpClientCallback>();
77      }
78  
79      @Override
80      public void doFilter(HttpServletRequest request, HttpServletResponse originalResponse, FilterChain chain) throws IOException, ServletException {
81          final StatusSniffingResponseWrapper response = new StatusSniffingResponseWrapper(originalResponse);
82          try {
83              chain.doFilter(request, response);
84              if (needsCallback(response)) {
85                  selectAndHandleCallback(request, response);
86              }
87          } catch (Throwable e) {
88              // an exception was thrown in the filter chain, let's see if it wraps an AccessDeniedException
89              if (wasCausedBy(e, javax.jcr.AccessDeniedException.class)) {
90                  response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
91                  selectAndHandleCallback(request, response);
92              } else {
93                  rethrow(e, IOException.class, ServletException.class);
94              }
95          }
96      }
97  
98      protected boolean needsCallback(StatusSniffingResponseWrapper response) {
99          final int status = response.getStatus();
100         return status == SC_FORBIDDEN || status == SC_UNAUTHORIZED;
101     }
102 
103     protected void selectAndHandleCallback(HttpServletRequest request, StatusSniffingResponseWrapper response) {
104         selectClientCallback(request).handle(request, response);
105     }
106 
107     protected HttpClientCallback selectClientCallback(HttpServletRequest request) {
108         for (HttpClientCallback clientCallback : clientCallbacks) {
109             if (clientCallback.accepts(request)) {
110                 return clientCallback;
111             }
112         }
113         throw new IllegalStateException("No configured callback accepted this request " + request.toString());
114     }
115 
116     // ---- configuration methods
117     public void addClientCallback(HttpClientCallback clientCallback) {
118         this.clientCallbacks.add(clientCallback);
119     }
120 
121     public void setClientCallbacks(List<HttpClientCallback> clientCallbacks) {
122         this.clientCallbacks.addAll(clientCallbacks);
123     }
124 
125     // TODO needs to be public to be seen by c2b!?
126     public List<HttpClientCallback> getClientCallbacks() {
127         return clientCallbacks;
128     }
129 
130     /**
131      * A simple HttpServletResponseWrapper which keeps track of the current http status code.
132      * Everything else is delegated to the parent response, which means calls to sendError or sendRedirect still mean
133      * the response is committed.
134      *
135      * Note: Will become obsolete with Servlet API 3.0 as it defines a publicly available HttpServletResponse#getStatus()
136      */
137     public static class StatusSniffingResponseWrapper extends HttpServletResponseWrapper {
138         private int status = SC_OK;
139 
140         public StatusSniffingResponseWrapper(HttpServletResponse response) {
141             super(response);
142         }
143 
144         public int getStatus() {
145             return status;
146         }
147 
148         @Override
149         public void reset() {
150             super.reset();
151             status = SC_OK;
152         }
153 
154         @Override
155         public void setStatus(int sc) {
156             super.setStatus(sc);
157             this.status = sc;
158         }
159 
160         @Override
161         public void setStatus(int sc, String sm) {
162             super.setStatus(sc, sm);
163             this.status = sc;
164         }
165 
166         @Override
167         public void sendRedirect(String location) throws IOException {
168             super.sendRedirect(location);
169             this.status = SC_MOVED_TEMPORARILY;
170         }
171 
172         @Override
173         public void sendError(int sc) throws IOException {
174             super.sendError(sc);
175             this.status = sc;
176         }
177 
178         @Override
179         public void sendError(int sc, String msg) throws IOException {
180             super.sendError(sc, msg);
181             this.status = sc;
182         }
183     }
184 }