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.HashMap;
22 import java.util.Iterator;
24 import java.util.Map.Entry;
26 import javax.security.auth.Subject;
27 import javax.servlet.RequestDispatcher;
28 import javax.servlet.ServletConfig;
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.authn.provider.PreviousSessionLoginHandler;
44 import edu.internet2.middleware.shibboleth.idp.profile.IdPProfileHandlerManager;
45 import edu.internet2.middleware.shibboleth.idp.session.AuthenticationMethodInformation;
46 import edu.internet2.middleware.shibboleth.idp.session.ServiceInformation;
47 import edu.internet2.middleware.shibboleth.idp.session.Session;
48 import edu.internet2.middleware.shibboleth.idp.session.impl.AuthenticationMethodInformationImpl;
49 import edu.internet2.middleware.shibboleth.idp.session.impl.ServiceInformationImpl;
52 * Manager responsible for handling authentication requests.
54 public class AuthenticationEngine extends HttpServlet {
56 /** Name of the IdP Cookie containing the IdP session ID. */
57 public static final String IDP_SESSION_COOKIE_NAME = "_idp_session";
59 /** Serial version UID. */
60 private static final long serialVersionUID = 8494202791991613148L;
63 private static final Logger LOG = LoggerFactory.getLogger(AuthenticationEngine.class);
65 /** Profile handler manager. */
66 private IdPProfileHandlerManager handlerManager;
68 /** Session manager. */
69 private SessionManager<Session> sessionManager;
72 public void init(ServletConfig config) throws ServletException {
75 String handlerManagerId = config.getInitParameter("handlerManagerId");
76 if (DatatypeHelper.isEmpty(handlerManagerId)) {
77 handlerManagerId = "shibboleth.HandlerManager";
79 handlerManager = (IdPProfileHandlerManager) getServletContext().getAttribute(handlerManagerId);
81 String sessionManagerId = config.getInitParameter("sessionManagedId");
82 if (DatatypeHelper.isEmpty(sessionManagerId)) {
83 sessionManagerId = "shibboleth.SessionManager";
86 sessionManager = (SessionManager<Session>) getServletContext().getAttribute(sessionManagerId);
90 * Returns control back to the authentication engine.
92 * @param httpRequest current http request
93 * @param httpResponse current http response
95 public static void returnToAuthenticationEngine(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
96 LOG.debug("Returning control to authentication engine");
97 HttpSession httpSession = httpRequest.getSession();
98 LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
99 if (loginContext == null) {
100 LOG.error("User HttpSession did not contain a login context. Unable to return to authentication engine");
101 forwardRequest("/idp-error.jsp", httpRequest, httpResponse);
103 forwardRequest(loginContext.getAuthenticationEngineURL(), httpRequest, httpResponse);
108 * Returns control back to the profile handler that invoked the authentication engine.
110 * @param loginContext current login context
111 * @param httpRequest current http request
112 * @param httpResponse current http response
114 public static void returnToProfileHandler(LoginContext loginContext, HttpServletRequest httpRequest,
115 HttpServletResponse httpResponse) {
116 LOG.debug("Returning control to profile handler at: {}", loginContext.getProfileHandlerURL());
117 httpRequest.getSession().removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
118 httpRequest.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
119 forwardRequest(loginContext.getProfileHandlerURL(), httpRequest, httpResponse);
123 * Forwards a request to the given path.
125 * @param forwardPath path to forward the request to
126 * @param httpRequest current HTTP request
127 * @param httpResponse current HTTP response
129 protected static void forwardRequest(String forwardPath, HttpServletRequest httpRequest,
130 HttpServletResponse httpResponse) {
132 RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(forwardPath);
133 dispatcher.forward(httpRequest, httpResponse);
135 } catch (IOException e) {
136 LOG.error("Unable to return control back to authentication engine", e);
137 } catch (ServletException e) {
138 LOG.error("Unable to return control back to authentication engine", e);
143 @SuppressWarnings("unchecked")
144 protected void service(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException,
146 LOG.debug("Processing incoming request");
148 if (httpResponse.isCommitted()) {
149 LOG.error("HTTP Response already committed");
152 LoginContext loginContext = (LoginContext) httpRequest.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
153 if (loginContext == null) {
154 // When the login context comes from the profile handlers its attached to the request
155 // The authn engine attaches it to the session to allow the handlers to do any number of
156 // request/response pairs without maintaining or losing the login context
157 loginContext = (LoginContext) httpRequest.getSession().getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
160 if (loginContext == null) {
161 LOG.error("Incoming request does not have attached login context");
162 throw new ServletException("Incoming request does not have attached login context");
165 if (!loginContext.getAuthenticationAttempted()) {
166 startUserAuthentication(loginContext, httpRequest, httpResponse);
168 completeAuthentication(loginContext, httpRequest, httpResponse);
173 * Begins the authentication process. Determines if forced re-authentication is required or if an existing, active,
174 * authentication method is sufficient. Also determines, when authentication is required, which handler to use
175 * depending on whether passive authentication is required.
177 * @param loginContext current login context
178 * @param httpRequest current HTTP request
179 * @param httpResponse current HTTP response
181 protected void startUserAuthentication(LoginContext loginContext, HttpServletRequest httpRequest,
182 HttpServletResponse httpResponse) {
183 LOG.debug("Beginning user authentication process");
185 Session idpSession = (Session) httpRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
186 if(idpSession != null){
187 LOG.debug("Existing IdP session available for principal {}", idpSession.getPrincipalName());
190 Map<String, LoginHandler> possibleLoginHandlers = determinePossibleLoginHandlers(loginContext);
191 LOG.debug("Possible authentication handlers for this request: {}", possibleLoginHandlers);
193 // Filter out possible candidate login handlers by forced and passive authentication requirements
194 if (loginContext.isForceAuthRequired()) {
195 filterByForceAuthentication(idpSession, loginContext, possibleLoginHandlers);
198 if (loginContext.isPassiveAuthRequired()) {
199 filterByPassiveAuthentication(loginContext, possibleLoginHandlers);
202 // If the user already has a session and its usage is acceptable than use it
203 // otherwise just use the first candidate login handler
204 if (idpSession != null
205 && possibleLoginHandlers.containsKey(PreviousSessionLoginHandler.PREVIOUS_SESSION_AUTHN_METHOD)) {
206 authenticateUserWithPreviousSession(loginContext, possibleLoginHandlers, httpRequest, httpResponse);
208 Entry<String, LoginHandler> chosenLoginHandler = possibleLoginHandlers.entrySet().iterator().next();
209 authenticateUser(chosenLoginHandler.getKey(), chosenLoginHandler.getValue(), loginContext, httpRequest,
212 } catch (AuthenticationException e) {
213 loginContext.setAuthenticationFailure(e);
214 returnToProfileHandler(loginContext, httpRequest, httpResponse);
219 * Determines which configured login handlers will support the requested authentication methods.
221 * @param loginContext current login context
223 * @return login methods that may be used to authenticate the user
225 * @throws AuthenticationException thrown if no login handler meets the given requirements
227 protected Map<String, LoginHandler> determinePossibleLoginHandlers(LoginContext loginContext)
228 throws AuthenticationException {
229 Map<String, LoginHandler> supportedLoginHandlers = new HashMap<String, LoginHandler>(handlerManager
230 .getLoginHandlers());
231 LOG.trace("Supported login handlers: {}", supportedLoginHandlers);
232 LOG.trace("Requested authentication methods: {}", loginContext.getRequestedAuthenticationMethods());
234 Iterator<Entry<String, LoginHandler>> supportedLoginHandlerItr = supportedLoginHandlers.entrySet().iterator();
235 Entry<String, LoginHandler> supportedLoginHandler;
236 while (supportedLoginHandlerItr.hasNext()) {
237 supportedLoginHandler = supportedLoginHandlerItr.next();
238 if (supportedLoginHandler.getKey().equals(PreviousSessionLoginHandler.PREVIOUS_SESSION_AUTHN_METHOD)
239 || !loginContext.getRequestedAuthenticationMethods().contains(supportedLoginHandler.getKey())) {
240 supportedLoginHandlerItr.remove();
245 if (supportedLoginHandlers.isEmpty()) {
246 LOG.error("No authentication method, requested by the service provider, is supported");
247 throw new AuthenticationException(
248 "No authentication method, requested by the service provider, is supported");
251 return supportedLoginHandlers;
255 * Filters out any login handler based on the requirement for forced authentication.
257 * During forced authentication any handler that has not previously been used to authenticate the user or any
258 * handlers that have been and support force re-authentication may be used. Filter out any of the other ones.
260 * @param idpSession user's current IdP session
261 * @param loginContext current login context
262 * @param loginHandlers login handlers to filter
264 * @throws ForceAuthenticationException thrown if no handlers remain after filtering
266 protected void filterByForceAuthentication(Session idpSession, LoginContext loginContext,
267 Map<String, LoginHandler> loginHandlers) throws ForceAuthenticationException {
268 LOG.debug("Forced authentication is required, filtering possible login handlers accordingly");
270 ArrayList<AuthenticationMethodInformation> activeMethods = new ArrayList<AuthenticationMethodInformation>();
271 if (idpSession != null) {
272 activeMethods.addAll(idpSession.getAuthenticationMethods().values());
275 LoginHandler loginHandler;
276 for (AuthenticationMethodInformation activeMethod : activeMethods) {
277 loginHandler = loginHandlers.get(activeMethod.getAuthenticationMethod());
278 if (loginHandler != null && !loginHandler.supportsForceAuthentication()) {
279 for (String handlerSupportedMethods : loginHandler.getSupportedAuthenticationMethods()) {
280 loginHandlers.remove(handlerSupportedMethods);
285 LOG.debug("Authentication handlers remaining after forced authentication requirement filtering: {}",
288 if (loginHandlers.isEmpty()) {
289 LOG.error("Force authentication required but no login handlers available to support it");
290 throw new ForceAuthenticationException();
295 * Filters out any login handler that doesn't support passive authentication if the login context indicates passive
296 * authentication is required.
298 * @param loginContext current login context
299 * @param loginHandlers login handlers to filter
301 * @throws PassiveAuthenticationException thrown if no handlers remain after filtering
303 protected void filterByPassiveAuthentication(LoginContext loginContext, Map<String, LoginHandler> loginHandlers)
304 throws PassiveAuthenticationException {
305 LOG.debug("Passive authentication is required, filtering poassible login handlers accordingly.");
307 LoginHandler loginHandler;
308 Iterator<Entry<String, LoginHandler>> authnMethodItr = loginHandlers.entrySet().iterator();
309 while (authnMethodItr.hasNext()) {
310 loginHandler = authnMethodItr.next().getValue();
311 if (!loginHandler.supportsPassive()) {
312 authnMethodItr.remove();
316 LOG.debug("Authentication handlers remaining after passive authentication requirement filtering: {}",
319 if (loginHandlers.isEmpty()) {
320 LOG.error("Passive authentication required but no login handlers available to support it");
321 throw new PassiveAuthenticationException();
326 * Completes the authentication request using an existing, active, authentication method for the current user.
328 * @param loginContext current login context
329 * @param possibleLoginHandlers login handlers that meet the peers authentication requirements
330 * @param httpRequest current HTTP request
331 * @param httpResponse current HTTP response
333 protected void authenticateUserWithPreviousSession(LoginContext loginContext,
334 Map<String, LoginHandler> possibleLoginHandlers, HttpServletRequest httpRequest,
335 HttpServletResponse httpResponse) {
336 LOG.debug("Authenticating user by way of existing session.");
338 Session idpSession = (Session) httpRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
339 PreviousSessionLoginHandler loginHandler = (PreviousSessionLoginHandler) handlerManager.getLoginHandlers().get(
340 PreviousSessionLoginHandler.PREVIOUS_SESSION_AUTHN_METHOD);
342 AuthenticationMethodInformation authenticationMethod = null;
343 for (String possibleAuthnMethod : possibleLoginHandlers.keySet()) {
344 authenticationMethod = idpSession.getAuthenticationMethods().get(possibleAuthnMethod);
345 if (authenticationMethod != null) {
350 if (loginHandler.reportPreviousSessionAuthnMethod()) {
351 loginContext.setAuthenticationDuration(loginHandler.getAuthenticationDuration());
352 loginContext.setAuthenticationInstant(new DateTime());
353 loginContext.setAuthenticationMethod(PreviousSessionLoginHandler.PREVIOUS_SESSION_AUTHN_METHOD);
355 loginContext.setAuthenticationDuration(authenticationMethod.getAuthenticationDuration());
356 loginContext.setAuthenticationInstant(authenticationMethod.getAuthenticationInstant());
357 loginContext.setAuthenticationMethod(authenticationMethod.getAuthenticationMethod());
359 loginContext.setPrincipalName(idpSession.getPrincipalName());
361 httpRequest.getSession().setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
362 loginHandler.login(httpRequest, httpResponse);
366 * Authenticates the user with the given authentication method provided by the given login handler.
368 * @param authnMethod the authentication method that will be used to authenticate the user
369 * @param loginHandler login handler that will authenticate user
370 * @param loginContext current login context
371 * @param httpRequest current HTTP request
372 * @param httpResponse current HTTP response
374 protected void authenticateUser(String authnMethod, LoginHandler loginHandler, LoginContext loginContext,
375 HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
376 LOG.debug("Authenticating user with login handler of type {}", loginHandler.getClass().getName());
378 loginContext.setAuthenticationAttempted();
379 loginContext.setAuthenticationInstant(new DateTime());
380 loginContext.setAuthenticationDuration(loginHandler.getAuthenticationDuration());
381 loginContext.setAuthenticationMethod(authnMethod);
382 loginContext.setAuthenticationEngineURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
383 httpRequest.getSession().setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
384 loginHandler.login(httpRequest, httpResponse);
388 * Completes the authentication process.
390 * The principal name set by the authentication handler is retrieved and pushed in to the login context, a
391 * Shibboleth session is created if needed, information indicating that the user has logged into the service is
392 * recorded and finally control is returned back to the profile handler.
394 * @param loginContext current login context
395 * @param httpRequest current HTTP request
396 * @param httpResponse current HTTP response
398 protected void completeAuthentication(LoginContext loginContext, HttpServletRequest httpRequest,
399 HttpServletResponse httpResponse) {
400 LOG.debug("Completing user authentication process");
402 // We check if the principal name was already set in the login context
403 // if not attempt to pull it from where login handlers are supposed to provide it
404 String principalName = DatatypeHelper.safeTrimOrNullString(loginContext.getPrincipalName());
405 if (principalName == null) {
406 principalName = DatatypeHelper.safeTrimOrNullString((String) httpRequest
407 .getAttribute(LoginHandler.PRINCIPAL_NAME_KEY));
408 if (principalName != null) {
409 loginContext.setPrincipalName(principalName);
411 loginContext.setPrincipalAuthenticated(false);
412 loginContext.setAuthenticationFailure(new AuthenticationException(
413 "No principal name returned from authentication handler."));
414 LOG.error("No principal name returned from authentication method: "
415 + loginContext.getAuthenticationMethod());
416 returnToProfileHandler(loginContext, httpRequest, httpResponse);
420 loginContext.setPrincipalAuthenticated(true);
422 // We allow a login handler to override the authentication method in the event that it supports multiple methods
423 String actualAuthnMethod = DatatypeHelper.safeTrimOrNullString((String) httpRequest
424 .getAttribute(LoginHandler.AUTHENTICATION_METHOD_KEY));
425 if (actualAuthnMethod != null) {
426 loginContext.setAuthenticationMethod(actualAuthnMethod);
429 LOG.debug("User {} authenticated with method {}", loginContext.getPrincipalName(), loginContext
430 .getAuthenticationMethod());
431 updateUserSession(loginContext, httpRequest, httpResponse);
432 returnToProfileHandler(loginContext, httpRequest, httpResponse);
436 * Updates the user's Shibboleth session with authentication information. If no session exists a new one will be
439 * @param loginContext current login context
440 * @param httpRequest current HTTP request
441 * @param httpResponse current HTTP response
443 protected void updateUserSession(LoginContext loginContext, HttpServletRequest httpRequest,
444 HttpServletResponse httpResponse) {
445 Session idpSession = (Session) httpRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
446 if (idpSession == null) {
447 LOG.debug("Creating shibboleth session for principal {}", loginContext.getPrincipalName());
448 idpSession = (Session) sessionManager.createSession(loginContext.getPrincipalName());
449 loginContext.setSessionID(idpSession.getSessionID());
450 addSessionCookie(httpRequest, httpResponse, idpSession);
453 LOG.debug("Recording authentication and service information in Shibboleth session for principal: {}",
454 loginContext.getPrincipalName());
455 Subject subject = (Subject) httpRequest.getAttribute(LoginHandler.SUBJECT_KEY);
456 String authnMethod = (String) httpRequest.getAttribute(LoginHandler.AUTHENTICATION_METHOD_KEY);
457 if (DatatypeHelper.isEmpty(authnMethod)) {
458 authnMethod = loginContext.getAuthenticationMethod();
461 AuthenticationMethodInformation authnMethodInfo = new AuthenticationMethodInformationImpl(subject, authnMethod,
462 loginContext.getAuthenticationInstant(), loginContext.getAuthenticationDuration());
464 idpSession.getAuthenticationMethods().put(authnMethodInfo.getAuthenticationMethod(), authnMethodInfo);
466 ServiceInformation serviceInfo = new ServiceInformationImpl(loginContext.getRelyingPartyId(), new DateTime(),
468 idpSession.getServicesInformation().put(serviceInfo.getEntityID(), serviceInfo);
472 * Adds an IdP session cookie to the outbound response.
474 * @param httpRequest current request
475 * @param httpResponse current response
476 * @param userSession user's session
478 protected void addSessionCookie(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
479 Session userSession) {
480 httpRequest.setAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE, userSession);
482 LOG.debug("Adding IdP session cookie to HTTP response");
483 Cookie sessionCookie = new Cookie(IDP_SESSION_COOKIE_NAME, userSession.getSessionID());
484 sessionCookie.setPath(httpRequest.getContextPath());
485 sessionCookie.setSecure(false);
486 sessionCookie.setMaxAge(-1);
488 httpResponse.addCookie(sessionCookie);