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;
26 import org.opensaml.common.SAMLObjectBuilder;
27 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
28 import org.opensaml.common.xml.SAMLConstants;
29 import org.opensaml.saml2.binding.AuthnResponseEndpointSelector;
30 import org.opensaml.saml2.core.AttributeStatement;
31 import org.opensaml.saml2.core.AuthnContext;
32 import org.opensaml.saml2.core.AuthnContextClassRef;
33 import org.opensaml.saml2.core.AuthnContextDeclRef;
34 import org.opensaml.saml2.core.AuthnRequest;
35 import org.opensaml.saml2.core.AuthnStatement;
36 import org.opensaml.saml2.core.RequestedAuthnContext;
37 import org.opensaml.saml2.core.Response;
38 import org.opensaml.saml2.core.Statement;
39 import org.opensaml.saml2.core.StatusCode;
40 import org.opensaml.saml2.core.Subject;
41 import org.opensaml.saml2.core.SubjectLocality;
42 import org.opensaml.saml2.metadata.AssertionConsumerService;
43 import org.opensaml.saml2.metadata.Endpoint;
44 import org.opensaml.saml2.metadata.EntityDescriptor;
45 import org.opensaml.saml2.metadata.IDPSSODescriptor;
46 import org.opensaml.saml2.metadata.SPSSODescriptor;
47 import org.opensaml.saml2.metadata.provider.MetadataProvider;
48 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
49 import org.opensaml.ws.message.decoder.MessageDecodingException;
50 import org.opensaml.ws.transport.http.HTTPInTransport;
51 import org.opensaml.ws.transport.http.HTTPOutTransport;
52 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
53 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
54 import org.opensaml.xml.io.MarshallingException;
55 import org.opensaml.xml.io.UnmarshallingException;
56 import org.opensaml.xml.security.SecurityException;
57 import org.opensaml.xml.util.DatatypeHelper;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
61 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
62 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
63 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
64 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
65 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
66 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
67 import edu.internet2.middleware.shibboleth.idp.authn.PassiveAuthenticationException;
68 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
69 import edu.internet2.middleware.shibboleth.idp.session.Session;
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();
130 LoginContext loginContext = (LoginContext) servletRequest.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
131 if (loginContext == null) {
132 log.debug("Incoming request does not contain a login context, processing as first leg of request");
133 performAuthentication(inTransport, outTransport);
135 log.debug("Incoming request contains a login context, processing as second leg of request");
136 completeAuthenticationRequest(inTransport, outTransport);
141 * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
142 * authenticating the user.
144 * @param inTransport inbound request transport
145 * @param outTransport outbound response transport
147 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
148 * authentication manager
150 protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
151 throws ProfileException {
152 HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
155 SSORequestContext requestContext = decodeRequest(inTransport, outTransport);
157 String relyingPartyId = requestContext.getInboundMessageIssuer();
158 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
159 ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(SSOConfiguration.PROFILE_ID);
160 if (ssoConfig == null) {
161 log.error("SAML 2 SSO profile is not configured for relying party "
162 + requestContext.getInboundMessageIssuer());
163 throw new ProfileException("SAML 2 SSO profile is not configured for relying party "
164 + requestContext.getInboundMessageIssuer());
167 log.debug("Creating login context and transferring control to authentication engine");
168 Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, requestContext.getRelayState(),
169 requestContext.getInboundSAMLMessage());
170 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
171 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(servletRequest));
172 if (loginContext.getRequestedAuthenticationMethods().size() == 0) {
173 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
176 servletRequest.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
177 RequestDispatcher dispatcher = servletRequest.getRequestDispatcher(authenticationManagerPath);
178 dispatcher.forward(servletRequest, ((HttpServletResponseAdapter) outTransport).getWrappedResponse());
179 } catch (MarshallingException e) {
180 log.error("Unable to marshall authentication request context");
181 throw new ProfileException("Unable to marshall authentication request context", e);
182 } catch (IOException ex) {
183 log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
184 throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
185 } catch (ServletException ex) {
186 log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
187 throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
192 * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
193 * party after they've been authenticated.
195 * @param inTransport inbound message transport
196 * @param outTransport outbound message transport
198 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
200 protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
201 throws ProfileException {
202 HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
204 Saml2LoginContext loginContext = (Saml2LoginContext) servletRequest.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
205 SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
207 checkSamlVersion(requestContext);
209 Response samlResponse;
211 if (loginContext.getAuthenticationFailure() != null) {
212 log.error("User authentication failed with the following error: {}", loginContext
213 .getAuthenticationFailure().toString());
215 if (loginContext.getAuthenticationFailure() instanceof PassiveAuthenticationException) {
216 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.NO_PASSIVE_URI,
219 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
222 throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
225 if (requestContext.getSubjectNameIdentifier() != null) {
227 .debug("Authentication request contained a subject with a name identifier, resolving principal from NameID");
228 resolvePrincipal(requestContext);
229 String requestedPrincipalName = requestContext.getPrincipalName();
230 if (!DatatypeHelper.safeEquals(loginContext.getPrincipalName(), requestedPrincipalName)) {
233 "Authentication request identified principal {} but authentication mechanism identified principal {}",
234 requestedPrincipalName, loginContext.getPrincipalName());
235 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
237 throw new ProfileException("User failed authentication");
241 resolveAttributes(requestContext);
243 ArrayList<Statement> statements = new ArrayList<Statement>();
244 statements.add(buildAuthnStatement(requestContext));
245 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
246 AttributeStatement attributeStatement = buildAttributeStatement(requestContext);
247 if (attributeStatement != null) {
248 requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
249 statements.add(attributeStatement);
253 samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
254 } catch (ProfileException e) {
255 samlResponse = buildErrorResponse(requestContext);
258 requestContext.setOutboundSAMLMessage(samlResponse);
259 requestContext.setOutboundSAMLMessageId(samlResponse.getID());
260 requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
261 encodeResponse(requestContext);
262 writeAuditLogEntry(requestContext);
266 * Decodes an incoming request and stores the information in a created request context.
268 * @param inTransport inbound transport
269 * @param outTransport outbound transport
271 * @return request context with decoded information
273 * @throws ProfileException thrown if the incoming message failed decoding
275 protected SSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
276 throws ProfileException {
277 log.debug("Decoding message with decoder binding {}", getInboundBinding());
278 SSORequestContext requestContext = new SSORequestContext();
279 requestContext.setMetadataProvider(getMetadataProvider());
280 requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
282 requestContext.setCommunicationProfileId(SSOConfiguration.PROFILE_ID);
283 requestContext.setInboundMessageTransport(inTransport);
284 requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
285 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
287 requestContext.setOutboundMessageTransport(outTransport);
288 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
291 SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
292 requestContext.setMessageDecoder(decoder);
293 decoder.decode(requestContext);
294 log.debug("Decoded request");
296 if (!(requestContext.getInboundMessage() instanceof AuthnRequest)) {
297 log.error("Incomming message was not a AuthnRequest, it was a {}", requestContext.getInboundMessage()
298 .getClass().getName());
299 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, null,
300 "Invalid SAML AuthnRequest message."));
301 throw new ProfileException("Invalid SAML AuthnRequest message.");
304 return requestContext;
305 } catch (MessageDecodingException e) {
306 log.error("Error decoding authentication request message", e);
307 throw new ProfileException("Error decoding authentication request message", e);
308 } catch (SecurityException e) {
309 log.error("Message did not meet security requirements", e);
310 throw new ProfileException("Message did not meet security requirements", e);
315 * Creates an authentication request context from the current environmental information.
317 * @param loginContext current login context
318 * @param in inbound transport
319 * @param out outbount transport
321 * @return created authentication request context
323 * @throws ProfileException thrown if there is a problem creating the context
325 protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
326 HTTPOutTransport out) throws ProfileException {
327 SSORequestContext requestContext = new SSORequestContext();
329 requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
331 requestContext.setLoginContext(loginContext);
332 requestContext.setPrincipalName(loginContext.getPrincipalName());
333 requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
334 requestContext.setUserSession(getUserSession(in));
335 requestContext.setRelayState(loginContext.getRelayState());
337 requestContext.setInboundMessageTransport(in);
338 requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
341 AuthnRequest authnRequest = loginContext.getAuthenticationRequest();
342 requestContext.setInboundMessage(authnRequest);
343 requestContext.setInboundSAMLMessage(loginContext.getAuthenticationRequest());
344 requestContext.setInboundSAMLMessageId(loginContext.getAuthenticationRequest().getID());
346 Subject authnSubject = authnRequest.getSubject();
347 if (authnSubject != null) {
348 requestContext.setSubjectNameIdentifier(authnSubject.getNameID());
350 } catch (UnmarshallingException e) {
351 log.error("Unable to unmarshall authentication request context");
352 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
353 "Error recovering request state"));
354 throw new ProfileException("Error recovering request state", e);
357 requestContext.setOutboundMessageTransport(out);
358 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
360 MetadataProvider metadataProvider = getMetadataProvider();
361 requestContext.setMetadataProvider(metadataProvider);
363 String relyingPartyId = loginContext.getRelyingPartyId();
364 requestContext.setInboundMessageIssuer(relyingPartyId);
366 EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
367 if (relyingPartyMetadata != null) {
368 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
369 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
370 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata
371 .getSPSSODescriptor(SAMLConstants.SAML20P_NS));
373 log.error("Unable to locate metadata for relying party ({})", relyingPartyId);
374 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
375 "Error locating relying party metadata"));
376 throw new ProfileException("Error locating relying party metadata");
378 } catch (MetadataProviderException e) {
379 log.error("Unable to locate metadata for relying party");
380 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
381 "Error locating relying party metadata"));
382 throw new ProfileException("Error locating relying party metadata");
385 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
386 if (rpConfig == null) {
387 log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
388 throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
391 requestContext.setRelyingPartyConfiguration(rpConfig);
393 SSOConfiguration profileConfig = (SSOConfiguration) rpConfig
394 .getProfileConfiguration(SSOConfiguration.PROFILE_ID);
395 requestContext.setProfileConfiguration(profileConfig);
396 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
397 requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
399 String assertingPartyId = rpConfig.getProviderId();
400 requestContext.setLocalEntityId(assertingPartyId);
401 requestContext.setOutboundMessageIssuer(assertingPartyId);
403 EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
404 if (localEntityDescriptor != null) {
405 requestContext.setLocalEntityMetadata(localEntityDescriptor);
406 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
407 requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
408 .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
410 } catch (MetadataProviderException e) {
411 log.error("Unable to locate metadata for asserting party");
412 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
413 "Error locating asserting party metadata"));
414 throw new ProfileException("Error locating asserting party metadata");
417 return requestContext;
421 * Creates an authentication statement for the current request.
423 * @param requestContext current request context
425 * @return constructed authentication statement
427 protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
428 Saml2LoginContext loginContext = requestContext.getLoginContext();
430 AuthnContext authnContext = buildAuthnContext(requestContext);
432 AuthnStatement statement = authnStatementBuilder.buildObject();
433 statement.setAuthnContext(authnContext);
434 statement.setAuthnInstant(loginContext.getAuthenticationInstant());
436 Session session = getUserSession(requestContext.getInboundMessageTransport());
437 if (session != null) {
438 statement.setSessionIndex(session.getSessionID());
441 if (loginContext.getAuthenticationDuration() > 0) {
442 statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
443 loginContext.getAuthenticationDuration()));
446 statement.setSubjectLocality(buildSubjectLocality(requestContext));
452 * Creates an {@link AuthnContext} for a succesful authentication request.
454 * @param requestContext current request
456 * @return the built authn context
458 protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
459 AuthnContext authnContext = authnContextBuilder.buildObject();
461 Saml2LoginContext loginContext = requestContext.getLoginContext();
462 AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
463 RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
464 if (requestedAuthnContext != null) {
465 if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
466 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
467 if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
468 AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
469 ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
470 authnContext.setAuthnContextClassRef(ref);
473 } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
474 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
475 if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
476 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
477 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
478 authnContext.setAuthnContextDeclRef(ref);
483 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
484 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
485 authnContext.setAuthnContextDeclRef(ref);
492 * Constructs the subject locality for the authentication statement.
494 * @param requestContext curent request context
496 * @return subject locality for the authentication statement
498 protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
499 HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
500 SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
501 subjectLocality.setAddress(transport.getPeerAddress());
502 subjectLocality.setDNSName(transport.getPeerDomainName());
504 return subjectLocality;
508 * Selects the appropriate endpoint for the relying party and stores it in the request context.
510 * @param requestContext current request context
512 * @return Endpoint selected from the information provided in the request context
514 protected Endpoint selectEndpoint(SSORequestContext requestContext) {
515 AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
516 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
517 endpointSelector.setMetadataProvider(getMetadataProvider());
518 endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
519 endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
520 endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
521 endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
522 return endpointSelector.selectEndpoint();
525 /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
526 protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
528 /** Current login context. */
529 private Saml2LoginContext loginContext;
532 * Gets the current login context.
534 * @return current login context
536 public Saml2LoginContext getLoginContext() {
541 * Sets the current login context.
543 * @param context current login context
545 public void setLoginContext(Saml2LoginContext context) {
546 loginContext = context;