2 * Copyright [2007] [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.profile.saml2;
19 import java.io.IOException;
20 import java.util.ArrayList;
22 import javax.servlet.RequestDispatcher;
23 import javax.servlet.ServletException;
24 import javax.servlet.http.HttpServletRequest;
25 import javax.servlet.http.HttpSession;
27 import org.opensaml.common.SAMLObjectBuilder;
28 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
29 import org.opensaml.common.xml.SAMLConstants;
30 import org.opensaml.saml2.binding.AuthnResponseEndpointSelector;
31 import org.opensaml.saml2.core.AttributeStatement;
32 import org.opensaml.saml2.core.AuthnContext;
33 import org.opensaml.saml2.core.AuthnContextClassRef;
34 import org.opensaml.saml2.core.AuthnContextDeclRef;
35 import org.opensaml.saml2.core.AuthnRequest;
36 import org.opensaml.saml2.core.AuthnStatement;
37 import org.opensaml.saml2.core.NameID;
38 import org.opensaml.saml2.core.RequestedAuthnContext;
39 import org.opensaml.saml2.core.Response;
40 import org.opensaml.saml2.core.Statement;
41 import org.opensaml.saml2.core.StatusCode;
42 import org.opensaml.saml2.core.Subject;
43 import org.opensaml.saml2.core.SubjectLocality;
44 import org.opensaml.saml2.metadata.AssertionConsumerService;
45 import org.opensaml.saml2.metadata.Endpoint;
46 import org.opensaml.saml2.metadata.EntityDescriptor;
47 import org.opensaml.saml2.metadata.IDPSSODescriptor;
48 import org.opensaml.saml2.metadata.SPSSODescriptor;
49 import org.opensaml.saml2.metadata.provider.MetadataProvider;
50 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
51 import org.opensaml.ws.message.decoder.MessageDecodingException;
52 import org.opensaml.ws.transport.http.HTTPInTransport;
53 import org.opensaml.ws.transport.http.HTTPOutTransport;
54 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
55 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
56 import org.opensaml.xml.io.MarshallingException;
57 import org.opensaml.xml.io.UnmarshallingException;
58 import org.opensaml.xml.security.SecurityException;
59 import org.opensaml.xml.util.DatatypeHelper;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
63 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
64 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
65 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
66 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
67 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
68 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
69 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
71 /** SAML 2.0 SSO request profile handler. */
72 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
75 private final Logger log = LoggerFactory.getLogger(SSOProfileHandler.class);
77 /** Builder of AuthnStatement objects. */
78 private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
80 /** Builder of AuthnContext objects. */
81 private SAMLObjectBuilder<AuthnContext> authnContextBuilder;
83 /** Builder of AuthnContextClassRef objects. */
84 private SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
86 /** Builder of AuthnContextDeclRef objects. */
87 private SAMLObjectBuilder<AuthnContextDeclRef> authnContextDeclRefBuilder;
89 /** Builder of SubjectLocality objects. */
90 private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
92 /** URL of the authentication manager servlet. */
93 private String authenticationManagerPath;
95 /** URI of request decoder. */
96 private String decodingBinding;
101 * @param authnManagerPath path to the authentication manager servlet
103 @SuppressWarnings("unchecked")
104 public SSOProfileHandler(String authnManagerPath) {
107 authenticationManagerPath = authnManagerPath;
109 authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) getBuilderFactory().getBuilder(
110 AuthnStatement.DEFAULT_ELEMENT_NAME);
111 authnContextBuilder = (SAMLObjectBuilder<AuthnContext>) getBuilderFactory().getBuilder(
112 AuthnContext.DEFAULT_ELEMENT_NAME);
113 authnContextClassRefBuilder = (SAMLObjectBuilder<AuthnContextClassRef>) getBuilderFactory().getBuilder(
114 AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
115 authnContextDeclRefBuilder = (SAMLObjectBuilder<AuthnContextDeclRef>) getBuilderFactory().getBuilder(
116 AuthnContextDeclRef.DEFAULT_ELEMENT_NAME);
117 subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
118 SubjectLocality.DEFAULT_ELEMENT_NAME);
122 public String getProfileId() {
123 return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:sso";
127 public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
128 HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
129 HttpSession httpSession = servletRequest.getSession(true);
130 LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
132 if (loginContext == null) {
133 log.debug("User session does not contain a login context, processing as first leg of request");
134 performAuthentication(inTransport, outTransport);
135 } else if (!loginContext.isPrincipalAuthenticated()) {
137 .debug("User session contained a login context but user was not authenticated, processing as first leg of request");
138 performAuthentication(inTransport, outTransport);
140 log.debug("User session contains a login context, processing as second leg of request");
141 completeAuthenticationRequest(inTransport, outTransport);
146 * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
147 * authenticating the user.
149 * @param inTransport inbound request transport
150 * @param outTransport outbound response transport
152 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
153 * authentication manager
155 protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
156 throws ProfileException {
157 HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
158 HttpSession httpSession = servletRequest.getSession();
161 SSORequestContext requestContext = decodeRequest(inTransport, outTransport);
163 String relyingPartyId = requestContext.getInboundMessageIssuer();
164 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
165 ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(SSOConfiguration.PROFILE_ID);
166 if (ssoConfig == null) {
167 log.error("SAML 2 SSO profile is not configured for relying party "
168 + requestContext.getInboundMessageIssuer());
169 throw new ProfileException("SAML 2 SSO profile is not configured for relying party "
170 + requestContext.getInboundMessageIssuer());
173 log.debug("Creating login context and transferring control to authentication engine");
174 Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, requestContext.getRelayState(),
175 requestContext.getInboundSAMLMessage());
176 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
177 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(servletRequest));
178 if (loginContext.getRequestedAuthenticationMethods().size() == 0) {
179 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
182 httpSession.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
183 RequestDispatcher dispatcher = servletRequest.getRequestDispatcher(authenticationManagerPath);
184 dispatcher.forward(servletRequest, ((HttpServletResponseAdapter) outTransport).getWrappedResponse());
185 } catch (MarshallingException e) {
186 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
187 log.error("Unable to marshall authentication request context");
188 throw new ProfileException("Unable to marshall authentication request context", e);
189 } catch (IOException ex) {
190 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
191 log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
192 throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
193 } catch (ServletException ex) {
194 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
195 log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
196 throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
201 * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
202 * party after they've been authenticated.
204 * @param inTransport inbound message transport
205 * @param outTransport outbound message transport
207 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
209 protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
210 throws ProfileException {
211 HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
212 HttpSession httpSession = servletRequest.getSession();
214 Saml2LoginContext loginContext = (Saml2LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
215 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
217 SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
219 checkSamlVersion(requestContext);
221 Response samlResponse;
223 if (loginContext.getPrincipalName() == null) {
224 log.error("User's login context did not contain a principal, user considered unauthenticiated.");
226 .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, null));
227 throw new ProfileException("User failed authentication");
230 if (requestContext.getSubjectNameIdentifier() != null) {
231 log.debug("Authentication request contained a subject with a name identifier, resolving principal from NameID");
232 resolvePrincipal(requestContext);
233 String requestedPrincipalName = requestContext.getPrincipalName();
234 if (!DatatypeHelper.safeEquals(loginContext.getPrincipalName(), requestedPrincipalName)) {
235 log.error("Authentication request identified principal {} but authentication mechanism identified principal {}",
236 requestedPrincipalName, loginContext.getPrincipalName());
237 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
239 throw new ProfileException("User failed authentication");
243 resolveAttributes(requestContext);
245 ArrayList<Statement> statements = new ArrayList<Statement>();
246 statements.add(buildAuthnStatement(requestContext));
247 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
248 AttributeStatement attributeStatement = buildAttributeStatement(requestContext);
249 if (attributeStatement != null) {
250 requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
251 statements.add(attributeStatement);
255 samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
256 } catch (ProfileException e) {
257 samlResponse = buildErrorResponse(requestContext);
260 requestContext.setOutboundSAMLMessage(samlResponse);
261 requestContext.setOutboundSAMLMessageId(samlResponse.getID());
262 requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
263 encodeResponse(requestContext);
264 writeAuditLogEntry(requestContext);
268 * Decodes an incoming request and stores the information in a created request context.
270 * @param inTransport inbound transport
271 * @param outTransport outbound transport
273 * @return request context with decoded information
275 * @throws ProfileException thrown if the incomming message failed decoding
277 protected SSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
278 throws ProfileException {
279 log.debug("Decoding message with decoder binding {}", decodingBinding);
281 SSORequestContext requestContext = new SSORequestContext();
282 requestContext.setMetadataProvider(getMetadataProvider());
283 requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
285 requestContext.setCommunicationProfileId(SSOConfiguration.PROFILE_ID);
286 requestContext.setInboundMessageTransport(inTransport);
287 requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
288 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
290 requestContext.setOutboundMessageTransport(outTransport);
291 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
294 SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
295 requestContext.setMessageDecoder(decoder);
296 decoder.decode(requestContext);
297 return requestContext;
298 } catch (MessageDecodingException e) {
299 log.error("Error decoding authentication request message", e);
300 throw new ProfileException("Error decoding authentication request message", e);
301 } catch (SecurityException e) {
302 log.error("Message did not meet security requirements", e);
303 throw new ProfileException("Message did not meet security requirements", e);
308 * Creates an authentication request context from the current environmental information.
310 * @param loginContext current login context
311 * @param in inbound transport
312 * @param out outbount transport
314 * @return created authentication request context
316 * @throws ProfileException thrown if there is a problem creating the context
318 protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
319 HTTPOutTransport out) throws ProfileException {
320 SSORequestContext requestContext = new SSORequestContext();
322 requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
324 requestContext.setLoginContext(loginContext);
325 requestContext.setPrincipalName(loginContext.getPrincipalName());
326 requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
327 requestContext.setUserSession(getUserSession(in));
328 requestContext.setRelayState(loginContext.getRelayState());
330 requestContext.setInboundMessageTransport(in);
331 requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
334 AuthnRequest authnRequest = loginContext.getAuthenticationRequest();
335 requestContext.setInboundMessage(authnRequest);
336 requestContext.setInboundSAMLMessage(loginContext.getAuthenticationRequest());
337 requestContext.setInboundSAMLMessageId(loginContext.getAuthenticationRequest().getID());
339 Subject authnSubject = authnRequest.getSubject();
340 if (authnSubject != null) {
341 requestContext.setSubjectNameIdentifier(authnSubject.getNameID());
343 } catch (UnmarshallingException e) {
344 log.error("Unable to unmarshall authentication request context");
345 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
346 "Error recovering request state"));
347 throw new ProfileException("Error recovering request state", e);
350 requestContext.setOutboundMessageTransport(out);
351 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
353 MetadataProvider metadataProvider = getMetadataProvider();
354 requestContext.setMetadataProvider(metadataProvider);
356 String relyingPartyId = loginContext.getRelyingPartyId();
357 requestContext.setInboundMessageIssuer(relyingPartyId);
359 EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
360 if (relyingPartyMetadata != null) {
361 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
362 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
363 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata
364 .getSPSSODescriptor(SAMLConstants.SAML20P_NS));
366 } catch (MetadataProviderException e) {
367 log.error("Unable to locate metadata for relying party");
368 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
369 "Error locating relying party metadata"));
370 throw new ProfileException("Error locating relying party metadata");
373 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
374 if (rpConfig == null) {
375 log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
376 throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
379 requestContext.setRelyingPartyConfiguration(rpConfig);
381 SSOConfiguration profileConfig = (SSOConfiguration) rpConfig
382 .getProfileConfiguration(SSOConfiguration.PROFILE_ID);
383 requestContext.setProfileConfiguration(profileConfig);
384 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
385 if (profileConfig.getSigningCredential() != null) {
386 requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
387 } else if (rpConfig.getDefaultSigningCredential() != null) {
388 requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
390 requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
392 String assertingPartyId = rpConfig.getProviderId();
393 requestContext.setLocalEntityId(assertingPartyId);
396 EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
397 if (localEntityDescriptor != null) {
398 requestContext.setLocalEntityMetadata(localEntityDescriptor);
399 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
400 requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
401 .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
403 } catch (MetadataProviderException e) {
404 log.error("Unable to locate metadata for asserting party");
405 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
406 "Error locating asserting party metadata"));
407 throw new ProfileException("Error locating asserting party metadata");
410 return requestContext;
414 * Creates an authentication statement for the current request.
416 * @param requestContext current request context
418 * @return constructed authentication statement
420 protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
421 Saml2LoginContext loginContext = requestContext.getLoginContext();
423 AuthnContext authnContext = buildAuthnContext(requestContext);
425 AuthnStatement statement = authnStatementBuilder.buildObject();
426 statement.setAuthnContext(authnContext);
427 statement.setAuthnInstant(loginContext.getAuthenticationInstant());
430 statement.setSessionIndex(null);
432 if (loginContext.getAuthenticationDuration() > 0) {
433 statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
434 loginContext.getAuthenticationDuration()));
437 statement.setSubjectLocality(buildSubjectLocality(requestContext));
443 * Creates an {@link AuthnContext} for a succesful authentication request.
445 * @param requestContext current request
447 * @return the built authn context
449 protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
450 AuthnContext authnContext = authnContextBuilder.buildObject();
452 Saml2LoginContext loginContext = requestContext.getLoginContext();
453 AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
454 RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
455 if (requestedAuthnContext != null) {
456 if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
457 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
458 if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
459 AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
460 ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
461 authnContext.setAuthnContextClassRef(ref);
464 } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
465 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
466 if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
467 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
468 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
469 authnContext.setAuthnContextDeclRef(ref);
474 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
475 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
476 authnContext.setAuthnContextDeclRef(ref);
483 * Constructs the subject locality for the authentication statement.
485 * @param requestContext curent request context
487 * @return subject locality for the authentication statement
489 protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
490 HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
491 SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
492 subjectLocality.setAddress(transport.getPeerAddress());
493 subjectLocality.setDNSName(transport.getPeerDomainName());
495 return subjectLocality;
499 * Selects the appropriate endpoint for the relying party and stores it in the request context.
501 * @param requestContext current request context
503 * @return Endpoint selected from the information provided in the request context
505 protected Endpoint selectEndpoint(SSORequestContext requestContext) {
506 AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
507 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
508 endpointSelector.setMetadataProvider(getMetadataProvider());
509 endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
510 endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
511 endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
512 endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
513 return endpointSelector.selectEndpoint();
516 /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
517 protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
519 /** Current login context. */
520 private Saml2LoginContext loginContext;
523 * Gets the current login context.
525 * @return current login context
527 public Saml2LoginContext getLoginContext() {
532 * Sets the current login context.
534 * @param context current login context
536 public void setLoginContext(Saml2LoginContext context) {
537 loginContext = context;