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