KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > info > magnolia > cms > security > SecurityFilter


1 /**
2  *
3  * Magnolia and its source-code is licensed under the LGPL.
4  * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
5  * When copying, adapting, or redistributing this document in keeping with the guidelines above,
6  * you are required to provide proper attribution to obinary.
7  * If you reproduce or distribute the document without making any substantive modifications to its content,
8  * please use the following attribution line:
9  *
10  * Copyright 1993-2006 obinary Ltd. (http://www.obinary.com) All rights reserved.
11  *
12  */

13 package info.magnolia.cms.security;
14
15 import info.magnolia.cms.beans.config.Server;
16 import info.magnolia.cms.core.Path;
17 import info.magnolia.cms.util.FreeMarkerUtil;
18
19 import java.io.IOException JavaDoc;
20 import java.util.Map JavaDoc;
21 import java.util.HashMap JavaDoc;
22
23 import javax.servlet.Filter JavaDoc;
24 import javax.servlet.FilterChain JavaDoc;
25 import javax.servlet.FilterConfig JavaDoc;
26 import javax.servlet.ServletException JavaDoc;
27 import javax.servlet.ServletRequest JavaDoc;
28 import javax.servlet.ServletResponse JavaDoc;
29 import javax.servlet.http.HttpServletRequest JavaDoc;
30 import javax.servlet.http.HttpServletResponse JavaDoc;
31 import javax.servlet.http.HttpSession JavaDoc;
32
33 import org.apache.commons.lang.StringUtils;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import freemarker.template.Template;
37
38
39 /**
40  * @author Fabrizio Giustina
41  * @version $Id: SecurityFilter.java 6947 2006-10-27 10:52:04Z gjoseph $
42  */

43 public class SecurityFilter implements Filter JavaDoc {
44
45     /**
46      * Logger.
47      */

48     private static Logger log = LoggerFactory.getLogger(SecurityFilter.class);
49
50     /**
51      * filter config login form
52      */

53     protected static final String JavaDoc LOGIN_FORM = "LoginForm";
54
55     /**
56      * filter config unsecured URI
57      */

58     protected static final String JavaDoc UNSECURED_URI = "UnsecuredPath";
59
60     /**
61      * Authentication type
62      */

63     protected static final String JavaDoc AUTH_TYPE = "AuthType";
64
65     /**
66      * Authentication type Basic
67      */

68     protected static final String JavaDoc AUTH_TYPE_BASIC = "Basic";
69
70     /**
71      * Authentication type Form
72      */

73     protected static final String JavaDoc AUTH_TYPE_FORM = "Form";
74
75     /**
76      * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
77      */

78     public void init(FilterConfig JavaDoc filterConfig) throws ServletException JavaDoc {
79         // unused
80
}
81
82     /**
83      * @see javax.servlet.Filter#destroy()
84      */

85     public void destroy() {
86         // unused
87
}
88
89     /**
90      * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
91      * javax.servlet.FilterChain)
92      */

93     public void doFilter(ServletRequest JavaDoc req, ServletResponse JavaDoc res, FilterChain JavaDoc chain) throws IOException JavaDoc,
94         ServletException JavaDoc {
95
96         HttpServletRequest JavaDoc request = (HttpServletRequest JavaDoc) req;
97         HttpServletResponse JavaDoc response = (HttpServletResponse JavaDoc) res;
98
99         if (isAllowed(request, response)) {
100             chain.doFilter(request, response);
101         }
102     }
103
104     /**
105      * Checks access from Listener / Authenticator / AccessLock.
106      * @param req HttpServletRequest as received by the service method
107      * @param res HttpServletResponse as received by the service method
108      * @return boolean <code>true</code> if access to the resource is allowed
109      * @throws IOException can be thrown when the servlet is unable to write to the response stream
110      */

111     protected boolean isAllowed(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res) throws IOException JavaDoc {
112         if (Lock.isSystemLocked()) {
113             res.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
114             return false;
115         }
116         else if (Authenticator.isAuthenticated(req)) {
117             return true;
118         }
119         else if (SecureURI.isUnsecure(Path.getURI(req))) {
120             return true;
121         }
122         else if (SecureURI.isProtected(Path.getURI(req))) {
123             return authenticate(req, res);
124         }
125         else if (!Listener.isAllowed(req)) {
126             res.sendError(HttpServletResponse.SC_FORBIDDEN);
127             return false;
128         }
129         return true;
130     }
131
132     /**
133      * Authenticate on basic headers.
134      * @param request HttpServletRequest
135      * @param response HttpServletResponse
136      * @return <code>true</code> if the user is authenticated
137      */

138     protected boolean authenticate(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
139         try {
140
141             String JavaDoc unsecuredUri = (String JavaDoc) Server.getInstance().getLoginConfig().get(UNSECURED_URI);
142
143             if (unsecuredUri != null) {
144                 if (Path.getURI(request).startsWith(unsecuredUri)) {
145                     return true;
146                 }
147             }
148
149             if (!Authenticator.authenticate(request)) {
150                 // invalidate previous session
151

152                 String JavaDoc authType = (String JavaDoc) Server.getInstance().getLoginConfig().get(AUTH_TYPE);
153
154                 HttpSession JavaDoc httpsession = request.getSession(false);
155                 if (httpsession != null) {
156                     httpsession.invalidate();
157                 }
158                 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
159
160                 if (StringUtils.equalsIgnoreCase(authType, AUTH_TYPE_FORM)
161                     && !StringUtils.equals(request.getParameter(AUTH_TYPE), AUTH_TYPE_BASIC)) { // override
162
String JavaDoc loginUrl = (String JavaDoc) Server.getInstance().getLoginConfig().get(LOGIN_FORM);
163                     log.debug("Using login url: {}", loginUrl);
164
165                     // Temporary check for conpatibility between dev builds, will be removed before RC4 release
166
// todo remove this check
167
if (StringUtils.equalsIgnoreCase(loginUrl, "/.resources/loginForm/login.html")) {
168                         loginUrl = "/mgnl-resources/loginForm/login.html";
169                         log.error("Incorrect login form", new Exception JavaDoc());
170                         log.error("config/server/LoginForm default value is changed to - /mgnl-resources/loginForm/login.html");
171                         log.error("Please bootstrap new config, or change the value manually ");
172                     }
173
174                     try {
175                         // we cannot use FreemarketUtil.process because MgnlContext is not set yet!
176
Template tmpl = FreeMarkerUtil.getDefaultConfiguration().getTemplate(loginUrl);
177                         Map JavaDoc data = new HashMap JavaDoc();
178                         data.put("contextPath", request.getContextPath());
179                         tmpl.process(data, response.getWriter());
180                     }
181                     catch (Exception JavaDoc e) {
182                         log.error("exception while writing login template", e);
183                     }
184                 }
185                 else {
186                     doBasicAuthentication(response);
187                 }
188
189                 return false;
190             }
191         }
192         catch (Exception JavaDoc e) {
193             log.error(e.getMessage(), e);
194             return false;
195         }
196
197         return true;
198     }
199
200     /**
201      * @param response
202      */

203     private void doBasicAuthentication(HttpServletResponse JavaDoc response) {
204         response.setHeader("WWW-Authenticate", "BASIC realm=\"" + Server.getBasicRealm() + "\"");
205     }
206
207 }
208
Popular Tags