]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.security.ui.rap/src/org/argeo/security/ui/rap/SecureEntryPoint.java
Start improving CMS login
[lgpl/argeo-commons.git] / org.argeo.security.ui.rap / src / org / argeo / security / ui / rap / SecureEntryPoint.java
1 /*
2 * Copyright (C) 2007-2012 Argeo GmbH
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.argeo.security.ui.rap;
17
18 import java.security.PrivilegedAction;
19
20 import javax.security.auth.Subject;
21 import javax.security.auth.callback.CallbackHandler;
22 import javax.security.auth.login.CredentialNotFoundException;
23 import javax.security.auth.login.LoginContext;
24 import javax.security.auth.login.LoginException;
25 import javax.servlet.http.HttpServletRequest;
26 import javax.servlet.http.HttpSession;
27
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30 import org.argeo.ArgeoException;
31 import org.argeo.cms.KernelHeader;
32 import org.argeo.cms.auth.ArgeoLoginContext;
33 import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
34 import org.argeo.security.ui.auth.DefaultLoginDialog;
35 import org.argeo.util.LocaleUtils;
36 import org.eclipse.jface.dialogs.MessageDialog;
37 import org.eclipse.rap.rwt.RWT;
38 import org.eclipse.rap.rwt.application.EntryPoint;
39 import org.eclipse.swt.widgets.Display;
40 import org.eclipse.ui.PlatformUI;
41 import org.springframework.security.authentication.BadCredentialsException;
42 import org.springframework.security.core.Authentication;
43 import org.springframework.security.core.context.SecurityContext;
44 import org.springframework.security.core.context.SecurityContextHolder;
45
46 /**
47 * RAP entry point with login capabilities. Once the user has been
48 * authenticated, the workbench is run as a privileged action by the related
49 * subject.
50 */
51 public class SecureEntryPoint implements EntryPoint {
52 private final static Log log = LogFactory.getLog(SecureEntryPoint.class);
53
54 /**
55 * From org.springframework.security.context.
56 * HttpSessionContextIntegrationFilter
57 */
58 protected static final String SPRING_SECURITY_CONTEXT_KEY = "SPRING_SECURITY_CONTEXT";
59
60 /**
61 * How many seconds to wait before invalidating the session if the user has
62 * not yet logged in.
63 */
64 private Integer loginTimeout = 1 * 60;
65 // TODO make it configurable
66 /** Default session timeout is 8 hours (European working day length) */
67 private Integer sessionTimeout = 8 * 60 * 60;
68
69 /** Override to provide an application specific workbench advisor */
70 protected RapWorkbenchAdvisor createRapWorkbenchAdvisor(String username) {
71 return new RapWorkbenchAdvisor(username);
72 }
73
74 @Override
75 public final int createUI() {
76 // Short login timeout so that the modal dialog login doesn't hang
77 // around too long
78 RWT.getRequest().getSession().setMaxInactiveInterval(loginTimeout);
79
80 // Try to load security context thanks to the session processing filter
81 // HttpServletRequest httpRequest = RWT.getRequest();
82 // HttpSession httpSession = httpRequest.getSession();
83 // Object contextFromSessionObject = httpSession
84 // .getAttribute(SPRING_SECURITY_CONTEXT_KEY);
85 // if (contextFromSessionObject != null)
86 // SecurityContextHolder
87 // .setContext((SecurityContext) contextFromSessionObject);
88
89 final Display display = PlatformUI.createDisplay();
90 Subject subject = new Subject();
91
92 final LoginContext loginContext;
93 try {
94 CallbackHandler callbackHandler = new DefaultLoginDialog(
95 display.getActiveShell());
96 loginContext = new ArgeoLoginContext(
97 KernelHeader.LOGIN_CONTEXT_USER, subject, callbackHandler);
98 } catch (LoginException e1) {
99 throw new ArgeoException("Cannot initialize login context", e1);
100 }
101
102 tryLogin: while (subject.getPrincipals(Authentication.class).size() == 0) {
103 try {
104 loginContext.login();
105 if (subject.getPrincipals(Authentication.class).size() == 0)
106 throw new ArgeoException("Login succeeded but no auth");// fatal
107
108 // add security context to session
109 // if (httpSession.getAttribute(SPRING_SECURITY_CONTEXT_KEY) == null)
110 // httpSession.setAttribute(SPRING_SECURITY_CONTEXT_KEY,
111 // SecurityContextHolder.getContext());
112
113 // add thread locale to RWT session
114 if (log.isTraceEnabled())
115 log.trace("Locale " + LocaleUtils.threadLocale.get());
116 RWT.setLocale(LocaleUtils.threadLocale.get());
117
118 // once the user is logged in, longer session timeout
119 RWT.getRequest().getSession()
120 .setMaxInactiveInterval(sessionTimeout);
121
122 if (log.isDebugEnabled())
123 log.debug("Authenticated " + subject);
124 } catch (LoginException e) {
125 BadCredentialsException bce = wasCausedByBadCredentials(e);
126 if (bce != null) {
127 MessageDialog.openInformation(display.getActiveShell(),
128 "Bad Credentials", bce.getMessage());
129 // retry login
130 continue tryLogin;
131 }
132 return processLoginDeath(display, e);
133 }
134 }
135
136 final String username = subject.getPrincipals(Authentication.class)
137 .iterator().next().getName();
138 // Logout callback when the display is disposed
139 display.disposeExec(new Runnable() {
140 public void run() {
141 if (log.isTraceEnabled())
142 log.trace("Display disposed");
143 try {
144 loginContext.logout();
145 } catch (LoginException e) {
146 log.error("Error when logging out", e);
147 }
148 }
149 });
150
151 //
152 // RUN THE WORKBENCH
153 //
154 Integer returnCode = null;
155 try {
156 returnCode = Subject.doAs(subject, new PrivilegedAction<Integer>() {
157 public Integer run() {
158 RapWorkbenchAdvisor workbenchAdvisor = createRapWorkbenchAdvisor(username);
159 int result = PlatformUI.createAndRunWorkbench(display,
160 workbenchAdvisor);
161 return new Integer(result);
162 }
163 });
164 // Explicit exit from workbench
165 fullLogout(loginContext, username);
166 } finally {
167 display.dispose();
168 }
169 return returnCode;
170 }
171
172 private Integer processLoginDeath(Display display, LoginException e) {
173 // check thread death
174 ThreadDeath td = wasCausedByThreadDeath(e);
175 if (td != null) {
176 display.dispose();
177 throw td;
178 }
179 if (!display.isDisposed()) {
180 ErrorFeedback.show("Unexpected exception during authentication", e);
181 // this was not just bad credentials or death thread
182 RWT.getRequest().getSession().setMaxInactiveInterval(1);
183 display.dispose();
184 return -1;
185 } else {
186 throw new ArgeoException(
187 "Unexpected exception during authentication", e);
188 }
189
190 }
191
192 /** Recursively look for {@link BadCredentialsException} in the root causes. */
193 private BadCredentialsException wasCausedByBadCredentials(Throwable t) {
194 if (t instanceof BadCredentialsException)
195 return (BadCredentialsException) t;
196
197 if (t instanceof CredentialNotFoundException)
198 return new BadCredentialsException("Login canceled");
199
200 if (t.getCause() != null)
201 return wasCausedByBadCredentials(t.getCause());
202 else
203 return null;
204 }
205
206 /**
207 * If there is a {@link ThreadDeath} in the root causes, rethrow it
208 * (important for RAP cleaning mechanism)
209 */
210 protected ThreadDeath wasCausedByThreadDeath(Throwable t) {
211 if (t instanceof ThreadDeath)
212 return (ThreadDeath) t;
213
214 if (t.getCause() != null)
215 return wasCausedByThreadDeath(t.getCause());
216 else
217 return null;
218 }
219
220 private void fullLogout(LoginContext loginContext, String username) {
221 try {
222 loginContext.logout();
223 SecurityContextHolder.clearContext();
224
225 // HttpServletRequest httpRequest = RWT.getRequest();
226 // HttpSession httpSession = httpRequest.getSession();
227 // httpSession.setAttribute(SPRING_SECURITY_CONTEXT_KEY, null);
228 RWT.getRequest().getSession().setMaxInactiveInterval(1);
229 log.info("Logged out " + (username != null ? username : "")
230 + " (THREAD=" + Thread.currentThread().getId() + ")");
231 } catch (LoginException e) {
232 log.error("Erorr when logging out", e);
233 }
234 }
235 }