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