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.ServletConfig;
30 import javax.servlet.ServletException;
31 import javax.servlet.http.Cookie;
32 import javax.servlet.http.HttpServlet;
33 import javax.servlet.http.HttpServletRequest;
34 import javax.servlet.http.HttpServletResponse;
35 import javax.servlet.http.HttpSession;
37 import org.joda.time.DateTime;
38 import org.opensaml.xml.util.DatatypeHelper;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 import edu.internet2.middleware.shibboleth.common.session.SessionManager;
43 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
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 completeAuthenticationWithoutActiveMethod(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 Map<String, LoginHandler> possibleLoginHandlers = determinePossibleLoginHandlers(loginContext);
186 ArrayList<AuthenticationMethodInformation> activeAuthnMethods = new ArrayList<AuthenticationMethodInformation>();
188 Session userSession = (Session) httpRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
189 if (userSession != null) {
190 activeAuthnMethods.addAll(userSession.getAuthenticationMethods().values());
193 if (loginContext.isForceAuthRequired()) {
194 LOG.debug("Forced authentication is required, filtering possible login handlers accordingly");
195 filterByForceAuthentication(loginContext, activeAuthnMethods, possibleLoginHandlers);
197 LOG.debug("Forced authentication not required, trying existing authentication methods");
198 for (AuthenticationMethodInformation activeAuthnMethod : activeAuthnMethods) {
199 if (possibleLoginHandlers.containsKey(activeAuthnMethod.getAuthenticationMethod())) {
200 completeAuthenticationWithActiveMethod(loginContext, activeAuthnMethod, httpRequest,
205 LOG.debug("No existing authentication method meets service provides requirements");
208 if (loginContext.isPassiveAuthRequired()) {
209 LOG.debug("Passive authentication is required, filtering poassibl login handlers accordingly.");
210 filterByPassiveAuthentication(loginContext, possibleLoginHandlers);
213 // Since we made it this far, just pick the first remaining login handler from the list
214 Entry<String, LoginHandler> chosenLoginHandler = possibleLoginHandlers.entrySet().iterator().next();
215 LOG.debug("Authenticating user with login handler of type {}", chosenLoginHandler.getValue().getClass()
217 authenticateUser(chosenLoginHandler.getKey(), chosenLoginHandler.getValue(), loginContext, httpRequest,
219 } catch (AuthenticationException e) {
220 loginContext.setAuthenticationFailure(e);
221 returnToProfileHandler(loginContext, httpRequest, httpResponse);
227 * Determines which configured login handlers will support the requested authentication methods.
229 * @param loginContext current login context
231 * @return login methods that may be used to authenticate the user
233 * @throws AuthenticationException thrown if no login handler meets the given requirements
235 protected Map<String, LoginHandler> determinePossibleLoginHandlers(LoginContext loginContext)
236 throws AuthenticationException {
237 Map<String, LoginHandler> supportedLoginHandlers = new HashMap<String, LoginHandler>(handlerManager
238 .getLoginHandlers());
239 LOG.trace("Supported login handlers: {}", supportedLoginHandlers);
240 LOG.trace("Requested authentication methods: {}", loginContext.getRequestedAuthenticationMethods());
242 Iterator<Entry<String, LoginHandler>> supportedLoginHandlerItr = supportedLoginHandlers.entrySet().iterator();
243 Entry<String, LoginHandler> supportedLoginHandler;
244 while (supportedLoginHandlerItr.hasNext()) {
245 supportedLoginHandler = supportedLoginHandlerItr.next();
246 if (!loginContext.getRequestedAuthenticationMethods().contains(supportedLoginHandler.getKey())) {
247 supportedLoginHandlerItr.remove();
252 if (supportedLoginHandlers.isEmpty()) {
253 LOG.error("No authentication method, requested by the service provider, is supported");
254 throw new AuthenticationException(
255 "No authentication method, requested by the service provider, is supported");
258 return supportedLoginHandlers;
262 * Filters out any login handler based on the requirement for forced authentication.
264 * During forced authentication any handler that has not previously been used to authenticate the the user or any
265 * handlers that have been and support force re-authentication may be used. Filter out any of the other ones.
267 * @param loginContext current login context
268 * @param activeAuthnMethods currently active authentication methods, never null
269 * @param loginHandlers login handlers to filter
271 * @throws ForceAuthenticationException thrown if no handlers remain after filtering
273 protected void filterByForceAuthentication(LoginContext loginContext,
274 Collection<AuthenticationMethodInformation> activeAuthnMethods, Map<String, LoginHandler> loginHandlers)
275 throws ForceAuthenticationException {
277 LoginHandler loginHandler;
278 for (AuthenticationMethodInformation activeAuthnMethod : activeAuthnMethods) {
279 loginHandler = loginHandlers.get(activeAuthnMethod.getAuthenticationMethod());
280 if (loginHandler != null && !loginHandler.supportsForceAuthentication()) {
281 for (String handlerSupportedMethods : loginHandler.getSupportedAuthenticationMethods()) {
282 loginHandlers.remove(handlerSupportedMethods);
287 if (loginHandlers.isEmpty()) {
288 LOG.error("Force authentication required but no login handlers available to support it");
289 throw new ForceAuthenticationException();
294 * Filters out any login handler that doesn't support passive authentication if the login context indicates passive
295 * authentication is required.
297 * @param loginContext current login context
298 * @param loginHandlers login handlers to filter
300 * @throws PassiveAuthenticationException thrown if no handlers remain after filtering
302 protected void filterByPassiveAuthentication(LoginContext loginContext, Map<String, LoginHandler> loginHandlers)
303 throws PassiveAuthenticationException {
304 LoginHandler loginHandler;
305 Iterator<Entry<String, LoginHandler>> authnMethodItr = loginHandlers.entrySet().iterator();
306 while (authnMethodItr.hasNext()) {
307 loginHandler = authnMethodItr.next().getValue();
308 if (!loginHandler.supportsPassive()) {
309 authnMethodItr.remove();
313 if (loginHandlers.isEmpty()) {
314 LOG.error("Passive authentication required but no login handlers available to support it");
315 throw new PassiveAuthenticationException();
320 * Authenticates the user with the given authentication method provided by the given login handler.
322 * @param authnMethod the authentication method that will be used to authenticate the user
323 * @param logingHandler login handler that will authenticate user
324 * @param loginContext current login context
325 * @param httpRequest current HTTP request
326 * @param httpResponse current HTTP response
328 protected void authenticateUser(String authnMethod, LoginHandler logingHandler, LoginContext loginContext,
329 HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
331 loginContext.setAuthenticationAttempted();
332 loginContext.setAuthenticationDuration(logingHandler.getAuthenticationDuration());
333 loginContext.setAuthenticationMethod(authnMethod);
334 loginContext.setAuthenticationEngineURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
335 httpRequest.getSession().setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
336 logingHandler.login(httpRequest, httpResponse);
340 * Completes the authentication request using an existing, active, authentication method for the current user.
342 * @param loginContext current login context
343 * @param authenticationMethod authentication method to use to complete the request
344 * @param httpRequest current HTTP request
345 * @param httpResponse current HTTP response
347 protected void completeAuthenticationWithActiveMethod(LoginContext loginContext,
348 AuthenticationMethodInformation authenticationMethod, HttpServletRequest httpRequest,
349 HttpServletResponse httpResponse) {
350 Session shibSession = (Session) httpRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
352 loginContext.setAuthenticationDuration(authenticationMethod.getAuthenticationDuration());
353 loginContext.setAuthenticationInstant(authenticationMethod.getAuthenticationInstant());
354 loginContext.setAuthenticationMethod(authenticationMethod.getAuthenticationMethod());
355 loginContext.setPrincipalAuthenticated(true);
356 loginContext.setPrincipalName(shibSession.getPrincipalName());
358 ServiceInformation serviceInfo = new ServiceInformationImpl(loginContext.getRelyingPartyId(), new DateTime(),
359 authenticationMethod);
360 shibSession.getServicesInformation().put(serviceInfo.getEntityID(), serviceInfo);
362 LOG.debug("Treating user {} as authenticated via existing method {}", loginContext.getPrincipalName(),
363 loginContext.getAuthenticationMethod());
364 returnToProfileHandler(loginContext, httpRequest, httpResponse);
368 * Completes the authentication process when and already active authentication mechanism wasn't used, that is, when
369 * the user was really authenticated.
371 * The principal name set by the authentication handler is retrieved and pushed in to the login context, a
372 * Shibboleth session is created if needed, information indicating that the user has logged into the service is
373 * recorded and finally control is returned back to the profile handler.
375 * @param loginContext current login context
376 * @param httpRequest current HTTP request
377 * @param httpResponse current HTTP response
379 protected void completeAuthenticationWithoutActiveMethod(LoginContext loginContext, HttpServletRequest httpRequest,
380 HttpServletResponse httpResponse) {
382 String principalName = DatatypeHelper.safeTrimOrNullString((String) httpRequest
383 .getAttribute(LoginHandler.PRINCIPAL_NAME_KEY));
384 if (principalName == null) {
385 loginContext.setPrincipalAuthenticated(false);
386 loginContext.setAuthenticationFailure(new AuthenticationException(
387 "No principal name returned from authentication handler."));
388 LOG.error("No principal name returned from authentication method: "
389 + loginContext.getAuthenticationMethod());
390 returnToProfileHandler(loginContext, httpRequest, httpResponse);
394 loginContext.setPrincipalAuthenticated(true);
395 loginContext.setPrincipalName(principalName);
396 loginContext.setAuthenticationInstant(new DateTime());
398 // We allow a login handler to override the authentication method in the event that it supports multiple methods
399 String actualAuthnMethod = DatatypeHelper.safeTrimOrNullString((String) httpRequest
400 .getAttribute(LoginHandler.AUTHENTICATION_METHOD_KEY));
401 if (actualAuthnMethod != null) {
402 loginContext.setAuthenticationMethod(actualAuthnMethod);
405 LOG.debug("User {} authenticated with method {}", loginContext.getPrincipalName(), loginContext
406 .getAuthenticationMethod());
407 updateUserSession(loginContext, httpRequest, httpResponse);
408 returnToProfileHandler(loginContext, httpRequest, httpResponse);
412 * Updates the user's Shibboleth session with authentication information. If no session exists a new one will be
415 * @param loginContext current login context
416 * @param httpRequest current HTTP request
417 * @param httpResponse current HTTP response
419 protected void updateUserSession(LoginContext loginContext, HttpServletRequest httpRequest,
420 HttpServletResponse httpResponse) {
421 Session shibSession = (Session) httpRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
422 if (shibSession == null) {
423 LOG.debug("Creating shibboleth session for principal {}", loginContext.getPrincipalName());
424 shibSession = (Session) sessionManager.createSession(loginContext.getPrincipalName());
425 loginContext.setSessionID(shibSession.getSessionID());
426 addSessionCookie(httpRequest, httpResponse, shibSession);
429 LOG.debug("Recording authentication and service information in Shibboleth session for principal: {}",
430 loginContext.getPrincipalName());
431 Subject subject = (Subject) httpRequest.getAttribute(LoginHandler.SUBJECT_KEY);
432 String authnMethod = (String) httpRequest.getAttribute(LoginHandler.AUTHENTICATION_METHOD_KEY);
433 if (DatatypeHelper.isEmpty(authnMethod)) {
434 authnMethod = loginContext.getAuthenticationMethod();
437 AuthenticationMethodInformation authnMethodInfo = new AuthenticationMethodInformationImpl(subject, authnMethod,
438 new DateTime(), loginContext.getAuthenticationDuration());
440 shibSession.getAuthenticationMethods().put(authnMethodInfo.getAuthenticationMethod(), authnMethodInfo);
442 ServiceInformation serviceInfo = new ServiceInformationImpl(loginContext.getRelyingPartyId(), new DateTime(),
444 shibSession.getServicesInformation().put(serviceInfo.getEntityID(), serviceInfo);
448 * Adds an IdP session cookie to the outbound response.
450 * @param httpRequest current request
451 * @param httpResponse current response
452 * @param userSession user's session
454 protected void addSessionCookie(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
455 Session userSession) {
456 httpRequest.setAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE, userSession);
458 LOG.debug("Adding IdP session cookie to HTTP response");
459 Cookie sessionCookie = new Cookie(IDP_SESSION_COOKIE_NAME, userSession.getSessionID());
460 sessionCookie.setPath(httpRequest.getContextPath());
461 sessionCookie.setSecure(false);
462 sessionCookie.setMaxAge(-1);
464 httpResponse.addCookie(sessionCookie);