2 * Copyright [2006] [University Corporation for Advanced Internet Development, Inc.]
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package edu.internet2.middleware.shibboleth.idp.authn;
19 import java.io.IOException;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.HashMap;
23 import java.util.Iterator;
25 import java.util.Map.Entry;
27 import javax.security.auth.Subject;
28 import javax.servlet.RequestDispatcher;
29 import javax.servlet.ServletException;
30 import javax.servlet.http.Cookie;
31 import javax.servlet.http.HttpServlet;
32 import javax.servlet.http.HttpServletRequest;
33 import javax.servlet.http.HttpServletResponse;
34 import javax.servlet.http.HttpSession;
36 import org.joda.time.DateTime;
37 import org.opensaml.xml.util.DatatypeHelper;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
41 import edu.internet2.middleware.shibboleth.common.session.SessionManager;
42 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
43 import edu.internet2.middleware.shibboleth.idp.profile.IdPProfileHandlerManager;
44 import edu.internet2.middleware.shibboleth.idp.session.AuthenticationMethodInformation;
45 import edu.internet2.middleware.shibboleth.idp.session.ServiceInformation;
46 import edu.internet2.middleware.shibboleth.idp.session.Session;
47 import edu.internet2.middleware.shibboleth.idp.session.impl.AuthenticationMethodInformationImpl;
48 import edu.internet2.middleware.shibboleth.idp.session.impl.ServiceInformationImpl;
51 * Manager responsible for handling authentication requests.
53 public class AuthenticationEngine extends HttpServlet {
55 /** Name of the IdP Cookie containing the IdP session ID. */
56 public static final String IDP_SESSION_COOKIE_NAME = "_idp_session";
58 /** Serial version UID. */
59 private static final long serialVersionUID = 8494202791991613148L;
62 private static final Logger LOG = LoggerFactory.getLogger(AuthenticationEngine.class);
65 * Gets the manager used to retrieve handlers for requests.
67 * @return manager used to retrieve handlers for requests
69 public IdPProfileHandlerManager getProfileHandlerManager() {
70 return (IdPProfileHandlerManager) getServletContext().getAttribute("handlerManager");
74 * Gets the session manager to be used.
76 * @return session manager to be used
78 @SuppressWarnings("unchecked")
79 public SessionManager<Session> getSessionManager() {
80 return (SessionManager<Session>) getServletContext().getAttribute("sessionManager");
84 * Returns control back to the authentication engine.
86 * @param httpRequest current http request
87 * @param httpResponse current http response
89 public static void returnToAuthenticationEngine(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
90 LOG.debug("Returning control to authentication engine");
91 HttpSession httpSession = httpRequest.getSession();
92 LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
93 if (loginContext == null) {
94 LOG.error("User HttpSession did not contain a login context. Unable to return to authentication engine");
96 forwardRequest(loginContext.getAuthenticationEngineURL(), httpRequest, httpResponse);
100 * Returns control back to the profile handler that invoked the authentication engine.
102 * @param loginContext current login context
103 * @param httpRequest current http request
104 * @param httpResponse current http response
106 public static void returnToProfileHandler(LoginContext loginContext, HttpServletRequest httpRequest,
107 HttpServletResponse httpResponse) {
108 LOG.debug("Returning control to profile handler at: {}", loginContext.getProfileHandlerURL());
109 forwardRequest(loginContext.getProfileHandlerURL(), httpRequest, httpResponse);
113 * Forwards a request to the given path.
115 * @param forwardPath path to forward the request to
116 * @param httpRequest current HTTP request
117 * @param httpResponse current HTTP response
119 protected static void forwardRequest(String forwardPath, HttpServletRequest httpRequest,
120 HttpServletResponse httpResponse) {
122 RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(forwardPath);
123 dispatcher.forward(httpRequest, httpResponse);
125 } catch (IOException e) {
126 LOG.error("Unable to return control back to authentication engine", e);
127 } catch (ServletException e) {
128 LOG.error("Unable to return control back to authentication engine", e);
133 @SuppressWarnings("unchecked")
134 protected void service(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException,
136 LOG.debug("Processing incoming request");
138 if (httpResponse.isCommitted()) {
139 LOG.error("HTTP Response already committed");
142 HttpSession httpSession = httpRequest.getSession();
143 LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
144 if (loginContext == null) {
145 LOG.error("Incoming request does not have attached login context");
146 throw new ServletException("Incoming request does not have attached login context");
149 if (!loginContext.getAuthenticationAttempted()) {
150 startUserAuthentication(loginContext, httpRequest, httpResponse);
152 completeAuthenticationWithoutActiveMethod(loginContext, httpRequest, httpResponse);
157 * Begins the authentication process. Determines if forced re-authentication is required or if an existing, active,
158 * authentication method is sufficient. Also determines, when authentication is required, which handler to use
159 * depending on whether passive authentication is required.
161 * @param loginContext current login context
162 * @param httpRequest current HTTP request
163 * @param httpResponse current HTTP response
165 protected void startUserAuthentication(LoginContext loginContext, HttpServletRequest httpRequest,
166 HttpServletResponse httpResponse) {
167 LOG.debug("Beginning user authentication process");
169 Map<String, LoginHandler> possibleLoginHandlers = determinePossibleLoginHandlers(loginContext);
170 ArrayList<AuthenticationMethodInformation> activeAuthnMethods = new ArrayList<AuthenticationMethodInformation>();
172 Session userSession = (Session) httpRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
173 if (userSession != null) {
174 activeAuthnMethods.addAll(userSession.getAuthenticationMethods().values());
177 if (loginContext.isForceAuthRequired()) {
178 LOG.debug("Forced authentication is required, filtering possible login handlers accordingly");
179 filterByForceAuthentication(loginContext, activeAuthnMethods, possibleLoginHandlers);
181 LOG.debug("Forced authentication not required, trying existing authentication methods");
182 for (AuthenticationMethodInformation activeAuthnMethod : activeAuthnMethods) {
183 if (possibleLoginHandlers.containsKey(activeAuthnMethod.getAuthenticationMethod())) {
184 completeAuthenticationWithActiveMethod(activeAuthnMethod, httpRequest, httpResponse);
188 LOG.debug("No existing authentication method meets service provides requirements");
191 if (loginContext.isPassiveAuthRequired()) {
192 LOG.debug("Passive authentication is required, filtering poassibl login handlers accordingly.");
193 filterByPassiveAuthentication(loginContext, possibleLoginHandlers);
196 // Since we made it this far, just pick the first remaining login handler from the list
197 Entry<String, LoginHandler> chosenLoginHandler = possibleLoginHandlers.entrySet().iterator().next();
198 LOG.debug("Authenticating user with login handler of type {}", chosenLoginHandler.getValue().getClass()
200 authenticateUser(chosenLoginHandler.getKey(), chosenLoginHandler.getValue(), loginContext, httpRequest,
202 } catch (AuthenticationException e) {
203 loginContext.setAuthenticationFailure(e);
204 returnToProfileHandler(loginContext, httpRequest, httpResponse);
210 * Determines which configured login handlers will support the requested authentication methods.
212 * @param loginContext current login context
214 * @return login methods that may be used to authenticate the user
216 * @throws AuthenticationException thrown if no login handler meets the given requirements
218 protected Map<String, LoginHandler> determinePossibleLoginHandlers(LoginContext loginContext)
219 throws AuthenticationException {
220 Map<String, LoginHandler> supportedLoginHandlers = new HashMap<String, LoginHandler>(getProfileHandlerManager()
221 .getLoginHandlers());
222 LOG.trace("Supported login handlers: {}", supportedLoginHandlers);
223 LOG.trace("Requested authentication methods: {}", loginContext.getRequestedAuthenticationMethods());
225 Iterator<Entry<String, LoginHandler>> supportedLoginHandlerItr = supportedLoginHandlers.entrySet().iterator();
226 Entry<String, LoginHandler> supportedLoginHandler;
227 while (supportedLoginHandlerItr.hasNext()) {
228 supportedLoginHandler = supportedLoginHandlerItr.next();
229 if (!loginContext.getRequestedAuthenticationMethods().contains(supportedLoginHandler.getKey())) {
230 supportedLoginHandlerItr.remove();
235 if (supportedLoginHandlers.isEmpty()) {
236 LOG.error("No authentication method, requested by the service provider, is supported");
237 throw new AuthenticationException(
238 "No authentication method, requested by the service provider, is supported");
241 return supportedLoginHandlers;
245 * Filters out any login handler based on the requirement for forced authentication.
247 * During forced authentication any handler that has not previously been used to authenticate the the user or any
248 * handlers that have been and support force re-authentication may be used. Filter out any of the other ones.
250 * @param loginContext current login context
251 * @param activeAuthnMethods currently active authentication methods, never null
252 * @param loginHandlers login handlers to filter
254 * @throws ForceAuthenticationException thrown if no handlers remain after filtering
256 protected void filterByForceAuthentication(LoginContext loginContext,
257 Collection<AuthenticationMethodInformation> activeAuthnMethods, Map<String, LoginHandler> loginHandlers)
258 throws ForceAuthenticationException {
260 LoginHandler loginHandler;
261 for (AuthenticationMethodInformation activeAuthnMethod : activeAuthnMethods) {
262 loginHandler = loginHandlers.get(activeAuthnMethod.getAuthenticationMethod());
263 if (loginHandler != null && !loginHandler.supportsForceAuthentication()) {
264 for (String handlerSupportedMethods : loginHandler.getSupportedAuthenticationMethods()) {
265 loginHandlers.remove(handlerSupportedMethods);
270 if (loginHandlers.isEmpty()) {
271 LOG.error("Force authentication required but no login handlers available to support it");
272 throw new ForceAuthenticationException();
277 * Filters out any login handler that doesn't support passive authentication if the login context indicates passive
278 * authentication is required.
280 * @param loginContext current login context
281 * @param loginHandlers login handlers to filter
283 * @throws PassiveAuthenticationException thrown if no handlers remain after filtering
285 protected void filterByPassiveAuthentication(LoginContext loginContext, Map<String, LoginHandler> loginHandlers)
286 throws PassiveAuthenticationException {
287 LoginHandler loginHandler;
288 Iterator<Entry<String, LoginHandler>> authnMethodItr = loginHandlers.entrySet().iterator();
289 while (authnMethodItr.hasNext()) {
290 loginHandler = authnMethodItr.next().getValue();
291 if (!loginHandler.supportsPassive()) {
292 authnMethodItr.remove();
296 if (loginHandlers.isEmpty()) {
297 LOG.error("Passive authentication required but no login handlers available to support it");
298 throw new PassiveAuthenticationException();
303 * Authenticates the user with the given authentication method provided by the given login handler.
305 * @param authnMethod the authentication method that will be used to authenticate the user
306 * @param logingHandler login handler that will authenticate user
307 * @param loginContext current login context
308 * @param httpRequest current HTTP request
309 * @param httpResponse current HTTP response
311 protected void authenticateUser(String authnMethod, LoginHandler logingHandler, LoginContext loginContext,
312 HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
314 loginContext.setAuthenticationAttempted();
315 loginContext.setAuthenticationDuration(logingHandler.getAuthenticationDuration());
316 loginContext.setAuthenticationMethod(authnMethod);
317 loginContext.setAuthenticationEngineURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
318 logingHandler.login(httpRequest, httpResponse);
322 * Completes the authentication request using an existing, active, authentication method for the current user.
324 * @param authenticationMethod authentication method to use to complete the request
325 * @param httpRequest current HTTP request
326 * @param httpResponse current HTTP response
328 protected void completeAuthenticationWithActiveMethod(AuthenticationMethodInformation authenticationMethod,
329 HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
330 HttpSession httpSession = httpRequest.getSession();
332 Session shibSession = (Session) httpRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
334 LOG.debug("Populating login context with existing session and authentication method information.");
335 LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
336 loginContext.setAuthenticationDuration(authenticationMethod.getAuthenticationDuration());
337 loginContext.setAuthenticationInstant(authenticationMethod.getAuthenticationInstant());
338 loginContext.setAuthenticationMethod(authenticationMethod.getAuthenticationMethod());
339 loginContext.setPrincipalAuthenticated(true);
340 loginContext.setPrincipalName(shibSession.getPrincipalName());
342 ServiceInformation serviceInfo = new ServiceInformationImpl(loginContext.getRelyingPartyId(), new DateTime(),
343 authenticationMethod);
344 shibSession.getServicesInformation().put(serviceInfo.getEntityID(), serviceInfo);
346 returnToProfileHandler(loginContext, httpRequest, httpResponse);
350 * Completes the authentication process when and already active authentication mechanism wasn't used, that is, when
351 * the user was really authenticated.
353 * The principal name set by the authentication handler is retrieved and pushed in to the login context, a
354 * Shibboleth session is created if needed, information indicating that the user has logged into the service is
355 * recorded and finally control is returned back to the profile handler.
357 * @param loginContext current login context
358 * @param httpRequest current HTTP request
359 * @param httpResponse current HTTP response
361 protected void completeAuthenticationWithoutActiveMethod(LoginContext loginContext, HttpServletRequest httpRequest,
362 HttpServletResponse httpResponse) {
364 String principalName = DatatypeHelper.safeTrimOrNullString((String) httpRequest
365 .getAttribute(LoginHandler.PRINCIPAL_NAME_KEY));
366 if (principalName == null) {
367 loginContext.setPrincipalAuthenticated(false);
368 loginContext.setAuthenticationFailure(new AuthenticationException(
369 "No principal name returned from authentication handler."));
370 LOG.error("No principal name returned from authentication method: "
371 + loginContext.getAuthenticationMethod());
372 returnToProfileHandler(loginContext, httpRequest, httpResponse);
376 loginContext.setPrincipalAuthenticated(true);
377 loginContext.setPrincipalName(principalName);
378 loginContext.setAuthenticationInstant(new DateTime());
380 // We allow a login handler to override the authentication method in the event that it supports multiple methods
381 String actualAuthnMethod = DatatypeHelper.safeTrimOrNullString((String) httpRequest
382 .getAttribute(LoginHandler.AUTHENTICATION_METHOD_KEY));
383 if (actualAuthnMethod != null) {
384 loginContext.setAuthenticationMethod(actualAuthnMethod);
387 updateUserSession(loginContext, httpRequest, httpResponse);
389 LOG.debug("User {} authentication with authentication method {}", loginContext.getPrincipalName(), loginContext
390 .getAuthenticationMethod());
392 returnToProfileHandler(loginContext, httpRequest, httpResponse);
396 * Updates the user's Shibboleth session with authentication information. If no session exists a new one will be
399 * @param loginContext current login context
400 * @param httpRequest current HTTP request
401 * @param httpResponse current HTTP response
403 protected void updateUserSession(LoginContext loginContext, HttpServletRequest httpRequest,
404 HttpServletResponse httpResponse) {
405 Session shibSession = (Session) httpRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
406 if (shibSession == null) {
407 LOG.debug("Creating shibboleth session for principal {}", loginContext.getPrincipalName());
408 shibSession = (Session) getSessionManager().createSession(loginContext.getPrincipalName());
409 loginContext.setSessionID(shibSession.getSessionID());
410 addSessionCookie(httpRequest, httpResponse, shibSession);
413 LOG.debug("Recording authentication and service information in Shibboleth session for principal: {}",
414 loginContext.getPrincipalName());
415 Subject subject = (Subject) httpRequest.getAttribute(LoginHandler.SUBJECT_KEY);
416 String authnMethod = (String) httpRequest.getAttribute(LoginHandler.AUTHENTICATION_METHOD_KEY);
417 if (DatatypeHelper.isEmpty(authnMethod)) {
418 authnMethod = loginContext.getAuthenticationMethod();
421 AuthenticationMethodInformation authnMethodInfo = new AuthenticationMethodInformationImpl(subject, authnMethod,
422 new DateTime(), loginContext.getAuthenticationDuration());
424 shibSession.getAuthenticationMethods().put(authnMethodInfo.getAuthenticationMethod(), authnMethodInfo);
426 ServiceInformation serviceInfo = new ServiceInformationImpl(loginContext.getRelyingPartyId(), new DateTime(),
428 shibSession.getServicesInformation().put(serviceInfo.getEntityID(), serviceInfo);
432 * Adds an IdP session cookie to the outbound response.
434 * @param httpRequest current request
435 * @param httpResponse current response
436 * @param userSession user's session
438 protected void addSessionCookie(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
439 Session userSession) {
440 httpRequest.setAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE, userSession);
442 LOG.debug("Adding IdP session cookie to HTTP response");
443 Cookie sessionCookie = new Cookie(IDP_SESSION_COOKIE_NAME, userSession.getSessionID());
444 sessionCookie.setPath(httpRequest.getContextPath());
445 sessionCookie.setSecure(false);
447 int maxAge = (int) (userSession.getInactivityTimeout() / 1000);
448 sessionCookie.setMaxAge(maxAge);
450 httpResponse.addCookie(sessionCookie);