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.net.InetAddress;
21 import java.net.UnknownHostException;
22 import java.util.List;
24 import javax.security.auth.Subject;
25 import javax.servlet.RequestDispatcher;
26 import javax.servlet.ServletException;
27 import javax.servlet.http.HttpServlet;
28 import javax.servlet.http.HttpServletRequest;
29 import javax.servlet.http.HttpServletResponse;
30 import javax.servlet.http.HttpSession;
32 import org.joda.time.DateTime;
33 import org.opensaml.xml.util.DatatypeHelper;
34 import org.opensaml.xml.util.Pair;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
38 import edu.internet2.middleware.shibboleth.common.session.SessionManager;
39 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
40 import edu.internet2.middleware.shibboleth.idp.profile.IdPProfileHandlerManager;
41 import edu.internet2.middleware.shibboleth.idp.session.AuthenticationMethodInformation;
42 import edu.internet2.middleware.shibboleth.idp.session.ServiceInformation;
43 import edu.internet2.middleware.shibboleth.idp.session.Session;
44 import edu.internet2.middleware.shibboleth.idp.session.impl.AuthenticationMethodInformationImpl;
45 import edu.internet2.middleware.shibboleth.idp.session.impl.ServiceInformationImpl;
48 * Manager responsible for handling authentication requests.
50 public class AuthenticationEngine extends HttpServlet {
52 /** Serial version UID. */
53 private static final long serialVersionUID = 8494202791991613148L;
56 private static final Logger LOG = LoggerFactory.getLogger(AuthenticationEngine.class);
59 * Gets the manager used to retrieve handlers for requests.
61 * @return manager used to retrieve handlers for requests
63 public IdPProfileHandlerManager getProfileHandlerManager() {
64 return (IdPProfileHandlerManager) getServletContext().getAttribute("handlerManager");
68 * Gets the session manager to be used.
70 * @return session manager to be used
72 @SuppressWarnings("unchecked")
73 public SessionManager<Session> getSessionManager() {
74 return (SessionManager<Session>) getServletContext().getAttribute("sessionManager");
78 * Returns control back to the authentication engine.
80 * @param httpRequest current http request
81 * @param httpResponse current http response
83 public static void returnToAuthenticationEngine(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
84 LOG.debug("Returning control to authentication engine");
85 HttpSession httpSession = httpRequest.getSession();
86 LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
87 if (loginContext == null) {
88 LOG.error("User HttpSession did not contain a login context. Unable to return to authentication engine");
90 forwardRequest(loginContext.getAuthenticationEngineURL(), httpRequest, httpResponse);
94 * Returns control back to the profile handler that invoked the authentication engine.
96 * @param loginContext current login context
97 * @param httpRequest current http request
98 * @param httpResponse current http response
100 public static void returnToProfileHandler(LoginContext loginContext, HttpServletRequest httpRequest,
101 HttpServletResponse httpResponse) {
102 LOG.debug("Returning control to profile handler at: {}", loginContext.getProfileHandlerURL());
103 forwardRequest(loginContext.getProfileHandlerURL(), httpRequest, httpResponse);
107 * Forwards a request to the given path.
109 * @param forwardPath path to forward the request to
110 * @param httpRequest current HTTP request
111 * @param httpResponse current HTTP response
113 protected static void forwardRequest(String forwardPath, HttpServletRequest httpRequest,
114 HttpServletResponse httpResponse) {
116 RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(forwardPath);
117 dispatcher.forward(httpRequest, httpResponse);
119 } catch (IOException e) {
120 LOG.error("Unable to return control back to authentication engine", e);
121 } catch (ServletException e) {
122 LOG.error("Unable to return control back to authentication engine", e);
127 @SuppressWarnings("unchecked")
128 protected void service(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException,
130 LOG.debug("Processing incoming request");
132 if (httpResponse.isCommitted()) {
133 LOG.error("HTTP Response already committed");
136 HttpSession httpSession = httpRequest.getSession();
137 LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
138 if (loginContext == null) {
139 LOG.error("Incoming request does not have attached login context");
140 throw new ServletException("Incoming request does not have attached login context");
143 if (!loginContext.getAuthenticationAttempted()) {
144 String shibSessionId = (String) httpSession.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
145 Session shibSession = getSessionManager().getSession(shibSessionId);
147 if (shibSession != null) {
148 AuthenticationMethodInformation authenticationMethod = getUsableExistingAuthenticationMethod(
149 loginContext, shibSession);
150 if (authenticationMethod != null) {
151 LOG.debug("An active authentication method is applicable for relying party. Using authentication "
152 + "method {} as authentication method to relying party without re-authenticating user.",
153 authenticationMethod.getAuthenticationMethod());
154 authenticateUserWithActiveMethod(httpRequest, httpResponse, authenticationMethod);
158 LOG.debug("No active authentication method is applicable for relying party. "
159 + "Authenticating user with to be determined method.");
160 authenticateUserWithoutActiveMethod1(httpRequest, httpResponse);
162 LOG.debug("Request returned from authentication handler, completing authentication process.");
163 authenticateUserWithoutActiveMethod2(httpRequest, httpResponse);
170 * Completes the authentication request using an existing, active, authentication method for the current user.
172 * @param httpRequest current HTTP request
173 * @param httpResponse current HTTP response
174 * @param authenticationMethod authentication method to use to complete the request
176 protected void authenticateUserWithActiveMethod(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
177 AuthenticationMethodInformation authenticationMethod) {
178 HttpSession httpSession = httpRequest.getSession();
180 String shibSessionId = (String) httpSession.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
181 Session shibSession = getSessionManager().getSession(shibSessionId);
183 LOG.debug("Populating login context with existing session and authentication method information.");
184 LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
185 loginContext.setAuthenticationDuration(authenticationMethod.getAuthenticationDuration());
186 loginContext.setAuthenticationInstant(authenticationMethod.getAuthenticationInstant());
187 loginContext.setAuthenticationMethod(authenticationMethod.getAuthenticationMethod());
188 loginContext.setPrincipalAuthenticated(true);
189 loginContext.setPrincipalName(shibSession.getPrincipalName());
191 ServiceInformation serviceInfo = new ServiceInformationImpl(loginContext.getRelyingPartyId(), new DateTime(),
192 authenticationMethod);
193 shibSession.getServicesInformation().put(serviceInfo.getEntityID(), serviceInfo);
195 returnToProfileHandler(loginContext, httpRequest, httpResponse);
199 * Performs the first part of user authentication. An authentication handler is determined, the login context is
200 * populated with some initial information, and control is forward to the selected handler so that it may
201 * authenticate the user.
203 * @param httpRequest current HTTP request
204 * @param httpResponse current HTTP response
206 protected void authenticateUserWithoutActiveMethod1(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
207 HttpSession httpSession = httpRequest.getSession();
208 LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
209 LOG.debug("Selecting appropriate authentication method for request.");
210 Pair<String, LoginHandler> handler = getProfileHandlerManager().getAuthenticationHandler(loginContext);
212 if (handler == null) {
213 loginContext.setPrincipalAuthenticated(false);
214 loginContext.setAuthenticationFailureMessage("No AuthenticationHandler satisfys the request from: "
215 + loginContext.getRelyingPartyId());
216 LOG.error("No AuthenticationHandler satisfies the request from relying party: "
217 + loginContext.getRelyingPartyId());
218 returnToProfileHandler(loginContext, httpRequest, httpResponse);
222 LOG.debug("Authentication method {} will be used to authenticate user.", handler.getFirst());
223 loginContext.setAuthenticationAttempted();
224 loginContext.setAuthenticationDuration(handler.getSecond().getAuthenticationDuration());
225 loginContext.setAuthenticationMethod(handler.getFirst());
226 loginContext.setAuthenticationEngineURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
228 LOG.debug("Transferring control to authentication handler of type: {}", handler.getSecond().getClass()
230 handler.getSecond().login(httpRequest, httpResponse);
234 * Performs the second part of user authentication. The principal name set by the authentication handler is
235 * retrieved and pushed in to the login context, a Shibboleth session is created if needed, information indicating
236 * that the user has logged into the service is recorded and finally control is returned back to the profile
239 * @param httpRequest current HTTP request
240 * @param httpResponse current HTTP response
242 protected void authenticateUserWithoutActiveMethod2(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
243 HttpSession httpSession = httpRequest.getSession();
245 String principalName = (String) httpRequest.getAttribute(LoginHandler.PRINCIPAL_NAME_KEY);
246 LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
247 if (DatatypeHelper.isEmpty(principalName)) {
248 loginContext.setPrincipalAuthenticated(false);
249 loginContext.setAuthenticationFailureMessage("No principal name returned from authentication handler.");
250 LOG.error("No principal name returned from authentication method: "
251 + loginContext.getAuthenticationMethod());
252 returnToProfileHandler(loginContext, httpRequest, httpResponse);
255 loginContext.setPrincipalAuthenticated(true);
256 loginContext.setPrincipalName(principalName);
257 loginContext.setAuthenticationInstant(new DateTime());
259 String shibSessionId = (String) httpSession.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
260 Session shibSession = getSessionManager().getSession(shibSessionId);
262 if (shibSession == null) {
263 LOG.debug("Creating shibboleth session for principal {}", principalName);
267 addr = InetAddress.getByName(httpRequest.getRemoteAddr());
268 } catch (UnknownHostException ex) {
272 shibSession = (Session) getSessionManager().createSession(addr, loginContext.getPrincipalName());
273 loginContext.setSessionID(shibSession.getSessionID());
274 httpSession.setAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE, shibSession.getSessionID());
277 LOG.debug("Recording authentication and service information in Shibboleth session for principal: {}",
279 Subject subject = (Subject) httpRequest.getAttribute(LoginHandler.SUBJECT_KEY);
280 AuthenticationMethodInformation authnMethodInfo = new AuthenticationMethodInformationImpl(subject, loginContext
281 .getAuthenticationMethod(), new DateTime(), loginContext.getAuthenticationDuration());
283 shibSession.getAuthenticationMethods().put(authnMethodInfo.getAuthenticationMethod(), authnMethodInfo);
285 ServiceInformation serviceInfo = new ServiceInformationImpl(loginContext.getRelyingPartyId(), new DateTime(),
287 shibSession.getServicesInformation().put(serviceInfo.getEntityID(), serviceInfo);
289 shibSession.setLastActivityInstant(new DateTime());
291 returnToProfileHandler(loginContext, httpRequest, httpResponse);
295 * Gets the authentication method, currently active for the user, that also meets the requirements expressed by the
296 * login context. If a method is returned the user does not need to authenticate again, if null is returned then the
297 * user must be authenticated.
299 * @param loginContext user login context
300 * @param shibSession user's shibboleth session
302 * @return active authentication method that meets authentication requirements or null
304 protected AuthenticationMethodInformation getUsableExistingAuthenticationMethod(LoginContext loginContext,
305 Session shibSession) {
306 if (loginContext.getForceAuth() || shibSession == null) {
310 List<String> preferredAuthnMethods = loginContext.getRequestedAuthenticationMethods();
312 if (preferredAuthnMethods == null || preferredAuthnMethods.size() == 0) {
313 for (AuthenticationMethodInformation authnMethod : shibSession.getAuthenticationMethods().values()) {
314 if (!authnMethod.isExpired()) {
319 for (String preferredAuthnMethod : preferredAuthnMethods) {
320 if (shibSession.getAuthenticationMethods().containsKey(preferredAuthnMethod)) {
321 AuthenticationMethodInformation authnMethodInfo = shibSession.getAuthenticationMethods().get(
322 preferredAuthnMethod);
323 if (!authnMethodInfo.isExpired()) {
324 return authnMethodInfo;