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 httpRequest.getSession().removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
110 httpRequest.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
111 forwardRequest(loginContext.getProfileHandlerURL(), httpRequest, httpResponse);
115 * Forwards a request to the given path.
117 * @param forwardPath path to forward the request to
118 * @param httpRequest current HTTP request
119 * @param httpResponse current HTTP response
121 protected static void forwardRequest(String forwardPath, HttpServletRequest httpRequest,
122 HttpServletResponse httpResponse) {
124 RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(forwardPath);
125 dispatcher.forward(httpRequest, httpResponse);
127 } catch (IOException e) {
128 LOG.error("Unable to return control back to authentication engine", e);
129 } catch (ServletException e) {
130 LOG.error("Unable to return control back to authentication engine", e);
135 @SuppressWarnings("unchecked")
136 protected void service(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException,
138 LOG.debug("Processing incoming request");
140 if (httpResponse.isCommitted()) {
141 LOG.error("HTTP Response already committed");
144 LoginContext loginContext = (LoginContext) httpRequest.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
145 if (loginContext == null) {
146 // When the login context comes from the profile handlers its attached to the request
147 // The authn engine attaches it to the session to allow the handlers to do any number of
148 // request/response pairs without maintaining or losing the login context
149 loginContext = (LoginContext) httpRequest.getSession().getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
152 if (loginContext == null) {
153 LOG.error("Incoming request does not have attached login context");
154 throw new ServletException("Incoming request does not have attached login context");
157 if (!loginContext.getAuthenticationAttempted()) {
158 startUserAuthentication(loginContext, httpRequest, httpResponse);
160 completeAuthenticationWithoutActiveMethod(loginContext, httpRequest, httpResponse);
165 * Begins the authentication process. Determines if forced re-authentication is required or if an existing, active,
166 * authentication method is sufficient. Also determines, when authentication is required, which handler to use
167 * depending on whether passive authentication is required.
169 * @param loginContext current login context
170 * @param httpRequest current HTTP request
171 * @param httpResponse current HTTP response
173 protected void startUserAuthentication(LoginContext loginContext, HttpServletRequest httpRequest,
174 HttpServletResponse httpResponse) {
175 LOG.debug("Beginning user authentication process");
177 Map<String, LoginHandler> possibleLoginHandlers = determinePossibleLoginHandlers(loginContext);
178 ArrayList<AuthenticationMethodInformation> activeAuthnMethods = new ArrayList<AuthenticationMethodInformation>();
180 Session userSession = (Session) httpRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
181 if (userSession != null) {
182 activeAuthnMethods.addAll(userSession.getAuthenticationMethods().values());
185 if (loginContext.isForceAuthRequired()) {
186 LOG.debug("Forced authentication is required, filtering possible login handlers accordingly");
187 filterByForceAuthentication(loginContext, activeAuthnMethods, possibleLoginHandlers);
189 LOG.debug("Forced authentication not required, trying existing authentication methods");
190 for (AuthenticationMethodInformation activeAuthnMethod : activeAuthnMethods) {
191 if (possibleLoginHandlers.containsKey(activeAuthnMethod.getAuthenticationMethod())) {
192 completeAuthenticationWithActiveMethod(loginContext, activeAuthnMethod, httpRequest,
197 LOG.debug("No existing authentication method meets service provides requirements");
200 if (loginContext.isPassiveAuthRequired()) {
201 LOG.debug("Passive authentication is required, filtering poassibl login handlers accordingly.");
202 filterByPassiveAuthentication(loginContext, possibleLoginHandlers);
205 // Since we made it this far, just pick the first remaining login handler from the list
206 Entry<String, LoginHandler> chosenLoginHandler = possibleLoginHandlers.entrySet().iterator().next();
207 LOG.debug("Authenticating user with login handler of type {}", chosenLoginHandler.getValue().getClass()
209 authenticateUser(chosenLoginHandler.getKey(), chosenLoginHandler.getValue(), loginContext, httpRequest,
211 } catch (AuthenticationException e) {
212 loginContext.setAuthenticationFailure(e);
213 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>(getProfileHandlerManager()
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 (!loginContext.getRequestedAuthenticationMethods().contains(supportedLoginHandler.getKey())) {
239 supportedLoginHandlerItr.remove();
244 if (supportedLoginHandlers.isEmpty()) {
245 LOG.error("No authentication method, requested by the service provider, is supported");
246 throw new AuthenticationException(
247 "No authentication method, requested by the service provider, is supported");
250 return supportedLoginHandlers;
254 * Filters out any login handler based on the requirement for forced authentication.
256 * During forced authentication any handler that has not previously been used to authenticate the the user or any
257 * handlers that have been and support force re-authentication may be used. Filter out any of the other ones.
259 * @param loginContext current login context
260 * @param activeAuthnMethods currently active authentication methods, never null
261 * @param loginHandlers login handlers to filter
263 * @throws ForceAuthenticationException thrown if no handlers remain after filtering
265 protected void filterByForceAuthentication(LoginContext loginContext,
266 Collection<AuthenticationMethodInformation> activeAuthnMethods, Map<String, LoginHandler> loginHandlers)
267 throws ForceAuthenticationException {
269 LoginHandler loginHandler;
270 for (AuthenticationMethodInformation activeAuthnMethod : activeAuthnMethods) {
271 loginHandler = loginHandlers.get(activeAuthnMethod.getAuthenticationMethod());
272 if (loginHandler != null && !loginHandler.supportsForceAuthentication()) {
273 for (String handlerSupportedMethods : loginHandler.getSupportedAuthenticationMethods()) {
274 loginHandlers.remove(handlerSupportedMethods);
279 if (loginHandlers.isEmpty()) {
280 LOG.error("Force authentication required but no login handlers available to support it");
281 throw new ForceAuthenticationException();
286 * Filters out any login handler that doesn't support passive authentication if the login context indicates passive
287 * authentication is required.
289 * @param loginContext current login context
290 * @param loginHandlers login handlers to filter
292 * @throws PassiveAuthenticationException thrown if no handlers remain after filtering
294 protected void filterByPassiveAuthentication(LoginContext loginContext, Map<String, LoginHandler> loginHandlers)
295 throws PassiveAuthenticationException {
296 LoginHandler loginHandler;
297 Iterator<Entry<String, LoginHandler>> authnMethodItr = loginHandlers.entrySet().iterator();
298 while (authnMethodItr.hasNext()) {
299 loginHandler = authnMethodItr.next().getValue();
300 if (!loginHandler.supportsPassive()) {
301 authnMethodItr.remove();
305 if (loginHandlers.isEmpty()) {
306 LOG.error("Passive authentication required but no login handlers available to support it");
307 throw new PassiveAuthenticationException();
312 * Authenticates the user with the given authentication method provided by the given login handler.
314 * @param authnMethod the authentication method that will be used to authenticate the user
315 * @param logingHandler login handler that will authenticate user
316 * @param loginContext current login context
317 * @param httpRequest current HTTP request
318 * @param httpResponse current HTTP response
320 protected void authenticateUser(String authnMethod, LoginHandler logingHandler, LoginContext loginContext,
321 HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
323 loginContext.setAuthenticationAttempted();
324 loginContext.setAuthenticationDuration(logingHandler.getAuthenticationDuration());
325 loginContext.setAuthenticationMethod(authnMethod);
326 loginContext.setAuthenticationEngineURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
327 httpRequest.getSession().setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
328 logingHandler.login(httpRequest, httpResponse);
332 * Completes the authentication request using an existing, active, authentication method for the current user.
334 * @param loginContext current login context
335 * @param authenticationMethod authentication method to use to complete the request
336 * @param httpRequest current HTTP request
337 * @param httpResponse current HTTP response
339 protected void completeAuthenticationWithActiveMethod(LoginContext loginContext,
340 AuthenticationMethodInformation authenticationMethod, HttpServletRequest httpRequest,
341 HttpServletResponse httpResponse) {
342 Session shibSession = (Session) httpRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
344 loginContext.setAuthenticationDuration(authenticationMethod.getAuthenticationDuration());
345 loginContext.setAuthenticationInstant(authenticationMethod.getAuthenticationInstant());
346 loginContext.setAuthenticationMethod(authenticationMethod.getAuthenticationMethod());
347 loginContext.setPrincipalAuthenticated(true);
348 loginContext.setPrincipalName(shibSession.getPrincipalName());
350 ServiceInformation serviceInfo = new ServiceInformationImpl(loginContext.getRelyingPartyId(), new DateTime(),
351 authenticationMethod);
352 shibSession.getServicesInformation().put(serviceInfo.getEntityID(), serviceInfo);
354 LOG.debug("Treating user {} as authenticated via existing method {}", loginContext.getPrincipalName(),
355 loginContext.getAuthenticationMethod());
356 returnToProfileHandler(loginContext, httpRequest, httpResponse);
360 * Completes the authentication process when and already active authentication mechanism wasn't used, that is, when
361 * the user was really authenticated.
363 * The principal name set by the authentication handler is retrieved and pushed in to the login context, a
364 * Shibboleth session is created if needed, information indicating that the user has logged into the service is
365 * recorded and finally control is returned back to the profile handler.
367 * @param loginContext current login context
368 * @param httpRequest current HTTP request
369 * @param httpResponse current HTTP response
371 protected void completeAuthenticationWithoutActiveMethod(LoginContext loginContext, HttpServletRequest httpRequest,
372 HttpServletResponse httpResponse) {
374 String principalName = DatatypeHelper.safeTrimOrNullString((String) httpRequest
375 .getAttribute(LoginHandler.PRINCIPAL_NAME_KEY));
376 if (principalName == null) {
377 loginContext.setPrincipalAuthenticated(false);
378 loginContext.setAuthenticationFailure(new AuthenticationException(
379 "No principal name returned from authentication handler."));
380 LOG.error("No principal name returned from authentication method: "
381 + loginContext.getAuthenticationMethod());
382 returnToProfileHandler(loginContext, httpRequest, httpResponse);
386 loginContext.setPrincipalAuthenticated(true);
387 loginContext.setPrincipalName(principalName);
388 loginContext.setAuthenticationInstant(new DateTime());
390 // We allow a login handler to override the authentication method in the event that it supports multiple methods
391 String actualAuthnMethod = DatatypeHelper.safeTrimOrNullString((String) httpRequest
392 .getAttribute(LoginHandler.AUTHENTICATION_METHOD_KEY));
393 if (actualAuthnMethod != null) {
394 loginContext.setAuthenticationMethod(actualAuthnMethod);
397 LOG.debug("User {} authenticated with method {}", loginContext.getPrincipalName(), loginContext
398 .getAuthenticationMethod());
399 updateUserSession(loginContext, httpRequest, httpResponse);
400 returnToProfileHandler(loginContext, httpRequest, httpResponse);
404 * Updates the user's Shibboleth session with authentication information. If no session exists a new one will be
407 * @param loginContext current login context
408 * @param httpRequest current HTTP request
409 * @param httpResponse current HTTP response
411 protected void updateUserSession(LoginContext loginContext, HttpServletRequest httpRequest,
412 HttpServletResponse httpResponse) {
413 Session shibSession = (Session) httpRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
414 if (shibSession == null) {
415 LOG.debug("Creating shibboleth session for principal {}", loginContext.getPrincipalName());
416 shibSession = (Session) getSessionManager().createSession(loginContext.getPrincipalName());
417 loginContext.setSessionID(shibSession.getSessionID());
418 addSessionCookie(httpRequest, httpResponse, shibSession);
421 LOG.debug("Recording authentication and service information in Shibboleth session for principal: {}",
422 loginContext.getPrincipalName());
423 Subject subject = (Subject) httpRequest.getAttribute(LoginHandler.SUBJECT_KEY);
424 String authnMethod = (String) httpRequest.getAttribute(LoginHandler.AUTHENTICATION_METHOD_KEY);
425 if (DatatypeHelper.isEmpty(authnMethod)) {
426 authnMethod = loginContext.getAuthenticationMethod();
429 AuthenticationMethodInformation authnMethodInfo = new AuthenticationMethodInformationImpl(subject, authnMethod,
430 new DateTime(), loginContext.getAuthenticationDuration());
432 shibSession.getAuthenticationMethods().put(authnMethodInfo.getAuthenticationMethod(), authnMethodInfo);
434 ServiceInformation serviceInfo = new ServiceInformationImpl(loginContext.getRelyingPartyId(), new DateTime(),
436 shibSession.getServicesInformation().put(serviceInfo.getEntityID(), serviceInfo);
440 * Adds an IdP session cookie to the outbound response.
442 * @param httpRequest current request
443 * @param httpResponse current response
444 * @param userSession user's session
446 protected void addSessionCookie(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
447 Session userSession) {
448 httpRequest.setAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE, userSession);
450 LOG.debug("Adding IdP session cookie to HTTP response");
451 Cookie sessionCookie = new Cookie(IDP_SESSION_COOKIE_NAME, userSession.getSessionID());
452 sessionCookie.setPath(httpRequest.getContextPath());
453 sessionCookie.setSecure(false);
455 int maxAge = (int) (userSession.getInactivityTimeout() / 1000);
456 sessionCookie.setMaxAge(maxAge);
458 httpResponse.addCookie(sessionCookie);