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 LoginContext loginContext = (LoginContext) httpRequest.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
143 if (loginContext == null) {
144 // When the login context comes from the profile handlers its attached to the request
145 // The authn engine attaches it to the session to allow the handlers to do any number of
146 // request/response pairs without maintaining or losing the login context
147 loginContext = (LoginContext) httpRequest.getSession().getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
149 // Clean out any old state that might be lying around
150 httpRequest.getSession().removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
153 if (loginContext == null) {
154 LOG.error("Incoming request does not have attached login context");
155 throw new ServletException("Incoming request does not have attached login context");
158 if (!loginContext.getAuthenticationAttempted()) {
159 startUserAuthentication(loginContext, httpRequest, httpResponse);
161 completeAuthenticationWithoutActiveMethod(loginContext, httpRequest, httpResponse);
166 * Begins the authentication process. Determines if forced re-authentication is required or if an existing, active,
167 * authentication method is sufficient. Also determines, when authentication is required, which handler to use
168 * depending on whether passive authentication is required.
170 * @param loginContext current login context
171 * @param httpRequest current HTTP request
172 * @param httpResponse current HTTP response
174 protected void startUserAuthentication(LoginContext loginContext, HttpServletRequest httpRequest,
175 HttpServletResponse httpResponse) {
176 LOG.debug("Beginning user authentication process");
178 Map<String, LoginHandler> possibleLoginHandlers = determinePossibleLoginHandlers(loginContext);
179 ArrayList<AuthenticationMethodInformation> activeAuthnMethods = new ArrayList<AuthenticationMethodInformation>();
181 Session userSession = (Session) httpRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
182 if (userSession != null) {
183 activeAuthnMethods.addAll(userSession.getAuthenticationMethods().values());
186 if (loginContext.isForceAuthRequired()) {
187 LOG.debug("Forced authentication is required, filtering possible login handlers accordingly");
188 filterByForceAuthentication(loginContext, activeAuthnMethods, possibleLoginHandlers);
190 LOG.debug("Forced authentication not required, trying existing authentication methods");
191 for (AuthenticationMethodInformation activeAuthnMethod : activeAuthnMethods) {
192 if (possibleLoginHandlers.containsKey(activeAuthnMethod.getAuthenticationMethod())) {
193 completeAuthenticationWithActiveMethod(loginContext, activeAuthnMethod, httpRequest,
198 LOG.debug("No existing authentication method meets service provides requirements");
201 if (loginContext.isPassiveAuthRequired()) {
202 LOG.debug("Passive authentication is required, filtering poassibl login handlers accordingly.");
203 filterByPassiveAuthentication(loginContext, possibleLoginHandlers);
206 // Since we made it this far, just pick the first remaining login handler from the list
207 Entry<String, LoginHandler> chosenLoginHandler = possibleLoginHandlers.entrySet().iterator().next();
208 LOG.debug("Authenticating user with login handler of type {}", chosenLoginHandler.getValue().getClass()
210 authenticateUser(chosenLoginHandler.getKey(), chosenLoginHandler.getValue(), loginContext, httpRequest,
212 } catch (AuthenticationException e) {
213 loginContext.setAuthenticationFailure(e);
214 returnToProfileHandler(loginContext, httpRequest, httpResponse);
220 * Determines which configured login handlers will support the requested authentication methods.
222 * @param loginContext current login context
224 * @return login methods that may be used to authenticate the user
226 * @throws AuthenticationException thrown if no login handler meets the given requirements
228 protected Map<String, LoginHandler> determinePossibleLoginHandlers(LoginContext loginContext)
229 throws AuthenticationException {
230 Map<String, LoginHandler> supportedLoginHandlers = new HashMap<String, LoginHandler>(getProfileHandlerManager()
231 .getLoginHandlers());
232 LOG.trace("Supported login handlers: {}", supportedLoginHandlers);
233 LOG.trace("Requested authentication methods: {}", loginContext.getRequestedAuthenticationMethods());
235 Iterator<Entry<String, LoginHandler>> supportedLoginHandlerItr = supportedLoginHandlers.entrySet().iterator();
236 Entry<String, LoginHandler> supportedLoginHandler;
237 while (supportedLoginHandlerItr.hasNext()) {
238 supportedLoginHandler = supportedLoginHandlerItr.next();
239 if (!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 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 loginContext current login context
261 * @param activeAuthnMethods currently active authentication methods, never null
262 * @param loginHandlers login handlers to filter
264 * @throws ForceAuthenticationException thrown if no handlers remain after filtering
266 protected void filterByForceAuthentication(LoginContext loginContext,
267 Collection<AuthenticationMethodInformation> activeAuthnMethods, Map<String, LoginHandler> loginHandlers)
268 throws ForceAuthenticationException {
270 LoginHandler loginHandler;
271 for (AuthenticationMethodInformation activeAuthnMethod : activeAuthnMethods) {
272 loginHandler = loginHandlers.get(activeAuthnMethod.getAuthenticationMethod());
273 if (loginHandler != null && !loginHandler.supportsForceAuthentication()) {
274 for (String handlerSupportedMethods : loginHandler.getSupportedAuthenticationMethods()) {
275 loginHandlers.remove(handlerSupportedMethods);
280 if (loginHandlers.isEmpty()) {
281 LOG.error("Force authentication required but no login handlers available to support it");
282 throw new ForceAuthenticationException();
287 * Filters out any login handler that doesn't support passive authentication if the login context indicates passive
288 * authentication is required.
290 * @param loginContext current login context
291 * @param loginHandlers login handlers to filter
293 * @throws PassiveAuthenticationException thrown if no handlers remain after filtering
295 protected void filterByPassiveAuthentication(LoginContext loginContext, Map<String, LoginHandler> loginHandlers)
296 throws PassiveAuthenticationException {
297 LoginHandler loginHandler;
298 Iterator<Entry<String, LoginHandler>> authnMethodItr = loginHandlers.entrySet().iterator();
299 while (authnMethodItr.hasNext()) {
300 loginHandler = authnMethodItr.next().getValue();
301 if (!loginHandler.supportsPassive()) {
302 authnMethodItr.remove();
306 if (loginHandlers.isEmpty()) {
307 LOG.error("Passive authentication required but no login handlers available to support it");
308 throw new PassiveAuthenticationException();
313 * Authenticates the user with the given authentication method provided by the given login handler.
315 * @param authnMethod the authentication method that will be used to authenticate the user
316 * @param logingHandler login handler that will authenticate user
317 * @param loginContext current login context
318 * @param httpRequest current HTTP request
319 * @param httpResponse current HTTP response
321 protected void authenticateUser(String authnMethod, LoginHandler logingHandler, LoginContext loginContext,
322 HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
324 loginContext.setAuthenticationAttempted();
325 loginContext.setAuthenticationDuration(logingHandler.getAuthenticationDuration());
326 loginContext.setAuthenticationMethod(authnMethod);
327 loginContext.setAuthenticationEngineURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
328 logingHandler.login(httpRequest, httpResponse);
329 httpRequest.getSession().setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
333 * Completes the authentication request using an existing, active, authentication method for the current user.
335 * @param loginContext current login context
336 * @param authenticationMethod authentication method to use to complete the request
337 * @param httpRequest current HTTP request
338 * @param httpResponse current HTTP response
340 protected void completeAuthenticationWithActiveMethod(LoginContext loginContext,
341 AuthenticationMethodInformation authenticationMethod, HttpServletRequest httpRequest,
342 HttpServletResponse httpResponse) {
343 Session shibSession = (Session) httpRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
345 loginContext.setAuthenticationDuration(authenticationMethod.getAuthenticationDuration());
346 loginContext.setAuthenticationInstant(authenticationMethod.getAuthenticationInstant());
347 loginContext.setAuthenticationMethod(authenticationMethod.getAuthenticationMethod());
348 loginContext.setPrincipalAuthenticated(true);
349 loginContext.setPrincipalName(shibSession.getPrincipalName());
351 ServiceInformation serviceInfo = new ServiceInformationImpl(loginContext.getRelyingPartyId(), new DateTime(),
352 authenticationMethod);
353 shibSession.getServicesInformation().put(serviceInfo.getEntityID(), serviceInfo);
355 LOG.debug("Treating user {} as authenticated via existing method {}", loginContext.getPrincipalName(),
356 loginContext.getAuthenticationMethod());
357 returnToProfileHandler(loginContext, httpRequest, httpResponse);
361 * Completes the authentication process when and already active authentication mechanism wasn't used, that is, when
362 * the user was really authenticated.
364 * The principal name set by the authentication handler is retrieved and pushed in to the login context, a
365 * Shibboleth session is created if needed, information indicating that the user has logged into the service is
366 * recorded and finally control is returned back to the profile handler.
368 * @param loginContext current login context
369 * @param httpRequest current HTTP request
370 * @param httpResponse current HTTP response
372 protected void completeAuthenticationWithoutActiveMethod(LoginContext loginContext, HttpServletRequest httpRequest,
373 HttpServletResponse httpResponse) {
375 String principalName = DatatypeHelper.safeTrimOrNullString((String) httpRequest
376 .getAttribute(LoginHandler.PRINCIPAL_NAME_KEY));
377 if (principalName == null) {
378 loginContext.setPrincipalAuthenticated(false);
379 loginContext.setAuthenticationFailure(new AuthenticationException(
380 "No principal name returned from authentication handler."));
381 LOG.error("No principal name returned from authentication method: "
382 + loginContext.getAuthenticationMethod());
383 returnToProfileHandler(loginContext, httpRequest, httpResponse);
387 loginContext.setPrincipalAuthenticated(true);
388 loginContext.setPrincipalName(principalName);
389 loginContext.setAuthenticationInstant(new DateTime());
391 // We allow a login handler to override the authentication method in the event that it supports multiple methods
392 String actualAuthnMethod = DatatypeHelper.safeTrimOrNullString((String) httpRequest
393 .getAttribute(LoginHandler.AUTHENTICATION_METHOD_KEY));
394 if (actualAuthnMethod != null) {
395 loginContext.setAuthenticationMethod(actualAuthnMethod);
398 updateUserSession(loginContext, httpRequest, httpResponse);
400 LOG.debug("User {} authentication with authentication method {}", loginContext.getPrincipalName(), loginContext
401 .getAuthenticationMethod());
403 returnToProfileHandler(loginContext, httpRequest, httpResponse);
407 * Updates the user's Shibboleth session with authentication information. If no session exists a new one will be
410 * @param loginContext current login context
411 * @param httpRequest current HTTP request
412 * @param httpResponse current HTTP response
414 protected void updateUserSession(LoginContext loginContext, HttpServletRequest httpRequest,
415 HttpServletResponse httpResponse) {
416 Session shibSession = (Session) httpRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
417 if (shibSession == null) {
418 LOG.debug("Creating shibboleth session for principal {}", loginContext.getPrincipalName());
419 shibSession = (Session) getSessionManager().createSession(loginContext.getPrincipalName());
420 loginContext.setSessionID(shibSession.getSessionID());
421 addSessionCookie(httpRequest, httpResponse, shibSession);
424 LOG.debug("Recording authentication and service information in Shibboleth session for principal: {}",
425 loginContext.getPrincipalName());
426 Subject subject = (Subject) httpRequest.getAttribute(LoginHandler.SUBJECT_KEY);
427 String authnMethod = (String) httpRequest.getAttribute(LoginHandler.AUTHENTICATION_METHOD_KEY);
428 if (DatatypeHelper.isEmpty(authnMethod)) {
429 authnMethod = loginContext.getAuthenticationMethod();
432 AuthenticationMethodInformation authnMethodInfo = new AuthenticationMethodInformationImpl(subject, authnMethod,
433 new DateTime(), loginContext.getAuthenticationDuration());
435 shibSession.getAuthenticationMethods().put(authnMethodInfo.getAuthenticationMethod(), authnMethodInfo);
437 ServiceInformation serviceInfo = new ServiceInformationImpl(loginContext.getRelyingPartyId(), new DateTime(),
439 shibSession.getServicesInformation().put(serviceInfo.getEntityID(), serviceInfo);
443 * Adds an IdP session cookie to the outbound response.
445 * @param httpRequest current request
446 * @param httpResponse current response
447 * @param userSession user's session
449 protected void addSessionCookie(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
450 Session userSession) {
451 httpRequest.setAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE, userSession);
453 LOG.debug("Adding IdP session cookie to HTTP response");
454 Cookie sessionCookie = new Cookie(IDP_SESSION_COOKIE_NAME, userSession.getSessionID());
455 sessionCookie.setPath(httpRequest.getContextPath());
456 sessionCookie.setSecure(false);
458 int maxAge = (int) (userSession.getInactivityTimeout() / 1000);
459 sessionCookie.setMaxAge(maxAge);
461 httpResponse.addCookie(sessionCookie);