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) {
153 "An active authentication method is applicable for relying party. "
154 + "Using authentication method {} as authentication method to relying party without re-authenticating user.",
155 authenticationMethod.getAuthenticationMethod());
156 authenticateUserWithActiveMethod(httpRequest, httpResponse, authenticationMethod);
160 LOG.debug("No active authentication method is applicable for relying party. "
161 + "Authenticating user with to be determined method.");
162 authenticateUserWithoutActiveMethod1(httpRequest, httpResponse);
164 LOG.debug("Request returned from authentication handler, completing authentication process.");
165 authenticateUserWithoutActiveMethod2(httpRequest, httpResponse);
172 * Completes the authentication request using an existing, active, authentication method for the current user.
174 * @param httpRequest current HTTP request
175 * @param httpResponse current HTTP response
176 * @param authenticationMethod authentication method to use to complete the request
178 protected void authenticateUserWithActiveMethod(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
179 AuthenticationMethodInformation authenticationMethod) {
180 HttpSession httpSession = httpRequest.getSession();
182 String shibSessionId = (String) httpSession.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
183 Session shibSession = getSessionManager().getSession(shibSessionId);
185 LOG.debug("Populating login context with existing session and authentication method information.");
186 LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
187 loginContext.setAuthenticationDuration(authenticationMethod.getAuthenticationDuration());
188 loginContext.setAuthenticationInstant(authenticationMethod.getAuthenticationInstant());
189 loginContext.setAuthenticationMethod(authenticationMethod.getAuthenticationMethod());
190 loginContext.setPrincipalAuthenticated(true);
191 loginContext.setPrincipalName(shibSession.getPrincipalName());
193 ServiceInformation serviceInfo = new ServiceInformationImpl(loginContext.getRelyingPartyId(), new DateTime(),
194 authenticationMethod);
195 shibSession.getServicesInformation().put(serviceInfo.getEntityID(), serviceInfo);
197 returnToProfileHandler(loginContext, httpRequest, httpResponse);
201 * Performs the first part of user authentication. An authentication handler is determined, the login context is
202 * populated with some initial information, and control is forward to the selected handler so that it may
203 * authenticate the user.
205 * @param httpRequest current HTTP request
206 * @param httpResponse current HTTP response
208 protected void authenticateUserWithoutActiveMethod1(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
209 HttpSession httpSession = httpRequest.getSession();
210 LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
211 LOG.debug("Selecting appropriate authentication method for request.");
212 Pair<String, LoginHandler> handler = getProfileHandlerManager().getAuthenticationHandler(loginContext);
214 if (handler == null) {
215 loginContext.setPrincipalAuthenticated(false);
216 loginContext.setAuthenticationFailureMessage("No AuthenticationHandler satisfys the request from: "
217 + loginContext.getRelyingPartyId());
218 LOG.error("No AuthenticationHandler satisfies the request from relying party: "
219 + loginContext.getRelyingPartyId());
220 returnToProfileHandler(loginContext, httpRequest, httpResponse);
224 LOG.debug("Authentication method {} will be used to authenticate user.", handler.getFirst());
225 loginContext.setAuthenticationAttempted();
226 loginContext.setAuthenticationDuration(handler.getSecond().getAuthenticationDuration());
227 loginContext.setAuthenticationMethod(handler.getFirst());
228 loginContext.setAuthenticationEngineURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
230 LOG.debug("Transferring control to authentication handler of type: {}", handler.getSecond().getClass()
232 handler.getSecond().login(httpRequest, httpResponse);
236 * Performs the second part of user authentication. The principal name set by the authentication handler is
237 * retrieved and pushed in to the login context, a Shibboleth session is created if needed, information indicating
238 * that the user has logged into the service is recorded and finally control is returned back to the profile
241 * @param httpRequest current HTTP request
242 * @param httpResponse current HTTP response
244 protected void authenticateUserWithoutActiveMethod2(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
245 HttpSession httpSession = httpRequest.getSession();
247 String principalName = (String) httpRequest.getAttribute(LoginHandler.PRINCIPAL_NAME_KEY);
248 LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
249 if (DatatypeHelper.isEmpty(principalName)) {
250 loginContext.setPrincipalAuthenticated(false);
251 loginContext.setAuthenticationFailureMessage("No principal name returned from authentication handler.");
252 LOG.error("No principal name returned from authentication method: "
253 + loginContext.getAuthenticationMethod());
254 returnToProfileHandler(loginContext, httpRequest, httpResponse);
257 loginContext.setPrincipalName(principalName);
258 loginContext.setAuthenticationInstant(new DateTime());
260 String shibSessionId = (String) httpSession.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
261 Session shibSession = getSessionManager().getSession(shibSessionId);
263 if (shibSession == null) {
264 LOG.debug("Creating shibboleth session for principal {}", principalName);
268 addr = InetAddress.getByName(httpRequest.getRemoteAddr());
269 } catch (UnknownHostException ex) {
273 shibSession = (Session) getSessionManager().createSession(addr, loginContext.getPrincipalName());
274 loginContext.setSessionID(shibSession.getSessionID());
275 httpSession.setAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE, shibSession.getSessionID());
278 LOG.debug("Recording authentication and service information in Shibboleth session for principal: {}",
280 Subject subject = (Subject) httpRequest.getAttribute(LoginHandler.SUBJECT_KEY);
281 AuthenticationMethodInformation authnMethodInfo = new AuthenticationMethodInformationImpl(subject, loginContext
282 .getAuthenticationMethod(), new DateTime(), loginContext.getAuthenticationDuration());
284 shibSession.getAuthenticationMethods().put(authnMethodInfo.getAuthenticationMethod(), authnMethodInfo);
286 ServiceInformation serviceInfo = new ServiceInformationImpl(loginContext.getRelyingPartyId(), new DateTime(),
288 shibSession.getServicesInformation().put(serviceInfo.getEntityID(), serviceInfo);
290 shibSession.setLastActivityInstant(new DateTime());
292 returnToProfileHandler(loginContext, httpRequest, httpResponse);
296 * Gets the authentication method, currently active for the user, that also meets the requirements expressed by the
297 * login context. If a method is returned the user does not need to authenticate again, if null is returned then the
298 * user must be authenticated.
300 * @param loginContext user login context
301 * @param shibSession user's shibboleth session
303 * @return active authentication method that meets authentication requirements or null
305 protected AuthenticationMethodInformation getUsableExistingAuthenticationMethod(LoginContext loginContext,
306 Session shibSession) {
307 if (loginContext.getForceAuth() || shibSession == null) {
311 List<String> preferredAuthnMethods = loginContext.getRequestedAuthenticationMethods();
313 if (preferredAuthnMethods == null || preferredAuthnMethods.size() == 0) {
314 for (AuthenticationMethodInformation authnMethod : shibSession.getAuthenticationMethods().values()) {
315 if (!authnMethod.isExpired()) {
320 for (String preferredAuthnMethod : preferredAuthnMethods) {
321 if (shibSession.getAuthenticationMethods().containsKey(preferredAuthnMethod)) {
322 AuthenticationMethodInformation authnMethodInfo = shibSession.getAuthenticationMethods().get(
323 preferredAuthnMethod);
324 if (!authnMethodInfo.isExpired()) {
325 return authnMethodInfo;