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.util.ArrayList;
20 import java.util.Collection;
21 import java.util.List;
24 import javax.servlet.ServletRequest;
25 import javax.servlet.ServletResponse;
27 import org.apache.log4j.Logger;
28 import org.joda.time.DateTime;
29 import org.opensaml.common.SAMLObjectBuilder;
30 import org.opensaml.common.SAMLVersion;
31 import org.opensaml.common.impl.SAMLObjectContentReference;
32 import org.opensaml.common.xml.SAMLConstants;
33 import org.opensaml.log.Level;
34 import org.opensaml.saml2.core.Advice;
35 import org.opensaml.saml2.core.Assertion;
36 import org.opensaml.saml2.core.AttributeQuery;
37 import org.opensaml.saml2.core.AttributeStatement;
38 import org.opensaml.saml2.core.Audience;
39 import org.opensaml.saml2.core.AudienceRestriction;
40 import org.opensaml.saml2.core.AuthnRequest;
41 import org.opensaml.saml2.core.Conditions;
42 import org.opensaml.saml2.core.Issuer;
43 import org.opensaml.saml2.core.NameID;
44 import org.opensaml.saml2.core.ProxyRestriction;
45 import org.opensaml.saml2.core.RequestAbstractType;
46 import org.opensaml.saml2.core.Response;
47 import org.opensaml.saml2.core.Statement;
48 import org.opensaml.saml2.core.Status;
49 import org.opensaml.saml2.core.StatusCode;
50 import org.opensaml.saml2.core.StatusMessage;
51 import org.opensaml.saml2.core.StatusResponseType;
52 import org.opensaml.saml2.core.Subject;
53 import org.opensaml.saml2.core.SubjectConfirmation;
54 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
55 import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor;
56 import org.opensaml.saml2.metadata.NameIDFormat;
57 import org.opensaml.saml2.metadata.PDPDescriptor;
58 import org.opensaml.saml2.metadata.RoleDescriptor;
59 import org.opensaml.saml2.metadata.SPSSODescriptor;
60 import org.opensaml.saml2.metadata.SSODescriptor;
61 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
62 import org.opensaml.xml.XMLObjectBuilder;
63 import org.opensaml.xml.security.credential.Credential;
64 import org.opensaml.xml.signature.Signature;
65 import org.opensaml.xml.signature.Signer;
66 import org.opensaml.xml.util.DatatypeHelper;
68 import edu.internet2.middleware.shibboleth.common.attribute.AttributeRequestException;
69 import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
70 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncoder;
71 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncodingException;
72 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML2AttributeAuthority;
73 import edu.internet2.middleware.shibboleth.common.attribute.provider.ShibbolethSAMLAttributeRequestContext;
74 import edu.internet2.middleware.shibboleth.common.log.AuditLogEntry;
75 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
76 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
77 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
78 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AbstractSAML2ProfileConfiguration;
79 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
80 import edu.internet2.middleware.shibboleth.idp.session.ServiceInformation;
81 import edu.internet2.middleware.shibboleth.idp.session.Session;
84 * Common implementation details for profile handlers.
86 public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHandler {
88 /** SAML Version for this profile handler. */
89 public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_20;
92 private Logger log = Logger.getLogger(AbstractSAML2ProfileHandler.class);
94 /** For building response. */
95 private SAMLObjectBuilder<Response> responseBuilder;
97 /** For building status. */
98 private SAMLObjectBuilder<Status> statusBuilder;
100 /** For building statuscode. */
101 private SAMLObjectBuilder<StatusCode> statusCodeBuilder;
103 /** For building StatusMessages. */
104 private SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
106 /** For building assertion. */
107 private SAMLObjectBuilder<Assertion> assertionBuilder;
109 /** For building issuer. */
110 private SAMLObjectBuilder<Issuer> issuerBuilder;
112 /** For building subject. */
113 private SAMLObjectBuilder<Subject> subjectBuilder;
115 /** For builder subject confirmation. */
116 private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
118 /** For building conditions. */
119 private SAMLObjectBuilder<Conditions> conditionsBuilder;
121 /** For building audience restriction. */
122 private SAMLObjectBuilder<AudienceRestriction> audienceRestrictionBuilder;
124 /** For building proxy retrictions. */
125 private SAMLObjectBuilder<ProxyRestriction> proxyRestrictionBuilder;
127 /** For building audience. */
128 private SAMLObjectBuilder<Audience> audienceBuilder;
130 /** For building advice. */
131 private SAMLObjectBuilder<Advice> adviceBuilder;
133 /** For building signature. */
134 private XMLObjectBuilder<Signature> signatureBuilder;
137 @SuppressWarnings("unchecked")
138 protected AbstractSAML2ProfileHandler() {
141 responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
142 statusBuilder = (SAMLObjectBuilder<Status>) getBuilderFactory().getBuilder(Status.DEFAULT_ELEMENT_NAME);
143 statusCodeBuilder = (SAMLObjectBuilder<StatusCode>) getBuilderFactory().getBuilder(
144 StatusCode.DEFAULT_ELEMENT_NAME);
145 statusMessageBuilder = (SAMLObjectBuilder<StatusMessage>) getBuilderFactory().getBuilder(
146 StatusMessage.DEFAULT_ELEMENT_NAME);
147 issuerBuilder = (SAMLObjectBuilder<Issuer>) getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
148 assertionBuilder = (SAMLObjectBuilder<Assertion>) getBuilderFactory()
149 .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
150 subjectBuilder = (SAMLObjectBuilder<Subject>) getBuilderFactory().getBuilder(Subject.DEFAULT_ELEMENT_NAME);
151 subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) getBuilderFactory().getBuilder(
152 SubjectConfirmation.DEFAULT_ELEMENT_NAME);
153 conditionsBuilder = (SAMLObjectBuilder<Conditions>) getBuilderFactory().getBuilder(
154 Conditions.DEFAULT_ELEMENT_NAME);
155 audienceRestrictionBuilder = (SAMLObjectBuilder<AudienceRestriction>) getBuilderFactory().getBuilder(
156 AudienceRestriction.DEFAULT_ELEMENT_NAME);
157 proxyRestrictionBuilder = (SAMLObjectBuilder<ProxyRestriction>) getBuilderFactory().getBuilder(
158 ProxyRestriction.DEFAULT_ELEMENT_NAME);
159 audienceBuilder = (SAMLObjectBuilder<Audience>) getBuilderFactory().getBuilder(Audience.DEFAULT_ELEMENT_NAME);
160 adviceBuilder = (SAMLObjectBuilder<Advice>) getBuilderFactory().getBuilder(Advice.DEFAULT_ELEMENT_NAME);
161 signatureBuilder = (XMLObjectBuilder<Signature>) getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
165 * Convenience method for getting the SAML 2 advice builder.
167 * @return SAML 2 advice builder
169 public SAMLObjectBuilder<Advice> getAdviceBuilder() {
170 return adviceBuilder;
174 * Convenience method for getting the SAML 2 assertion builder.
176 * @return SAML 2 assertion builder
178 public SAMLObjectBuilder<Assertion> getAssertionBuilder() {
179 return assertionBuilder;
183 * Convenience method for getting the SAML 2 audience builder.
185 * @return SAML 2 audience builder
187 public SAMLObjectBuilder<Audience> getAudienceBuilder() {
188 return audienceBuilder;
192 * Convenience method for getting the SAML 2 audience restriction builder.
194 * @return SAML 2 audience restriction builder
196 public SAMLObjectBuilder<AudienceRestriction> getAudienceRestrictionBuilder() {
197 return audienceRestrictionBuilder;
201 * Convenience method for getting the SAML 2 conditions builder.
203 * @return SAML 2 conditions builder
205 public SAMLObjectBuilder<Conditions> getConditionsBuilder() {
206 return conditionsBuilder;
210 * Convenience method for getting the SAML 2 Issuer builder.
212 * @return SAML 2 Issuer builder
214 public SAMLObjectBuilder<Issuer> getIssuerBuilder() {
215 return issuerBuilder;
219 * Convenience method for getting the SAML 2 proxy restriction builder.
221 * @return SAML 2 proxy restriction builder
223 public SAMLObjectBuilder<ProxyRestriction> getProxyRestrictionBuilder() {
224 return proxyRestrictionBuilder;
228 * Convenience method for getting the SAML 2 response builder.
230 * @return SAML 2 response builder
232 public SAMLObjectBuilder<Response> getResponseBuilder() {
233 return responseBuilder;
237 * Convenience method for getting the Signature builder.
239 * @return signature builder
241 public XMLObjectBuilder<Signature> getSignatureBuilder() {
242 return signatureBuilder;
246 * Convenience method for getting the SAML 2 status builder.
248 * @return SAML 2 status builder
250 public SAMLObjectBuilder<Status> getStatusBuilder() {
251 return statusBuilder;
255 * Convenience method for getting the SAML 2 status code builder.
257 * @return SAML 2 status code builder
259 public SAMLObjectBuilder<StatusCode> getStatusCodeBuilder() {
260 return statusCodeBuilder;
264 * Convenience method for getting the SAML 2 status message builder.
266 * @return SAML 2 status message builder
268 public SAMLObjectBuilder<StatusMessage> getStatusMessageBuilder() {
269 return statusMessageBuilder;
273 * Convenience method for getting the SAML 2 subject builder.
275 * @return SAML 2 subject builder
277 public SAMLObjectBuilder<Subject> getSubjectBuilder() {
278 return subjectBuilder;
282 * Convenience method for getting the SAML 2 subject confirmation builder.
284 * @return SAML 2 subject confirmation builder
286 public SAMLObjectBuilder<SubjectConfirmation> getSubjectConfirmationBuilder() {
287 return subjectConfirmationBuilder;
291 * Builds a response to the attribute query within the request context.
293 * @param requestContext current request context
294 * @param assertionSubject subject of the assertion within the response
295 * @param statements the statements to include in the response
297 * @return the built response
299 * @throws ProfileException thrown if there is a problem creating the SAML response
301 protected Response buildResponse(SAML2ProfileRequestContext requestContext, Subject assertionSubject,
302 List<Statement> statements) throws ProfileException {
304 DateTime issueInstant = new DateTime();
306 // create the assertion and add the attribute statement
307 Assertion assertion = buildAssertion(requestContext, issueInstant);
308 assertion.setSubject(assertionSubject);
309 if (statements != null) {
310 assertion.getStatements().addAll(statements);
313 // create the SAML response and add the assertion
314 Response samlResponse = getResponseBuilder().buildObject();
315 samlResponse.setIssueInstant(issueInstant);
316 populateStatusResponse(requestContext, samlResponse);
318 samlResponse.getAssertions().add(assertion);
320 // sign the assertion if it should be signed
321 signAssertion(requestContext, assertion);
323 Status status = buildStatus(StatusCode.SUCCESS_URI, null, null);
324 samlResponse.setStatus(status);
330 * Builds a basic assertion with its id, issue instant, SAML version, issuer, subject, and conditions populated.
332 * @param requestContext current request context
333 * @param issueInstant time to use as assertion issue instant
335 * @return the built assertion
337 protected Assertion buildAssertion(SAML2ProfileRequestContext requestContext, DateTime issueInstant) {
338 Assertion assertion = getAssertionBuilder().buildObject();
339 assertion.setID(getIdGenerator().generateIdentifier());
340 assertion.setIssueInstant(issueInstant);
341 assertion.setVersion(SAMLVersion.VERSION_20);
342 assertion.setIssuer(buildEntityIssuer(requestContext));
344 Conditions conditions = buildConditions(requestContext, issueInstant);
345 assertion.setConditions(conditions);
351 * Creates an {@link Issuer} populated with information about the relying party.
353 * @param requestContext current request context
355 * @return the built issuer
357 protected Issuer buildEntityIssuer(SAML2ProfileRequestContext requestContext) {
358 Issuer issuer = getIssuerBuilder().buildObject();
359 issuer.setFormat(Issuer.ENTITY);
360 issuer.setValue(requestContext.getRelyingPartyId());
366 * Builds a SAML assertion condition set. The following fields are set; not before, not on or after, audience
367 * restrictions, and proxy restrictions.
369 * @param requestContext current request context
370 * @param issueInstant timestamp the assertion was created
372 * @return constructed conditions
374 protected Conditions buildConditions(SAML2ProfileRequestContext requestContext, DateTime issueInstant) {
375 AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
377 Conditions conditions = getConditionsBuilder().buildObject();
378 conditions.setNotBefore(issueInstant);
379 conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
381 Collection<String> audiences;
383 // add audience restrictions
384 audiences = profileConfig.getAssertionAudiences();
385 if (audiences != null && audiences.size() > 0) {
386 AudienceRestriction audienceRestriction = getAudienceRestrictionBuilder().buildObject();
387 for (String audienceUri : audiences) {
388 Audience audience = getAudienceBuilder().buildObject();
389 audience.setAudienceURI(audienceUri);
390 audienceRestriction.getAudiences().add(audience);
392 conditions.getAudienceRestrictions().add(audienceRestriction);
395 // add proxy restrictions
396 audiences = profileConfig.getProxyAudiences();
397 if (audiences != null && audiences.size() > 0) {
398 ProxyRestriction proxyRestriction = getProxyRestrictionBuilder().buildObject();
400 for (String audienceUri : audiences) {
401 audience = getAudienceBuilder().buildObject();
402 audience.setAudienceURI(audienceUri);
403 proxyRestriction.getAudiences().add(audience);
406 proxyRestriction.setProxyCount(profileConfig.getProxyCount());
407 conditions.getConditions().add(proxyRestriction);
414 * Populates the response's id, in response to, issue instant, version, and issuer properties.
416 * @param requestContext current request context
417 * @param response the response to populate
419 protected void populateStatusResponse(SAML2ProfileRequestContext requestContext, StatusResponseType response) {
420 response.setID(getIdGenerator().generateIdentifier());
421 if (requestContext.getSamlRequest() != null) {
422 response.setInResponseTo(requestContext.getSamlRequest().getID());
424 response.setVersion(SAMLVersion.VERSION_20);
425 response.setIssuer(buildEntityIssuer(requestContext));
429 * Executes a query for attributes and builds a SAML attribute statement from the results.
431 * @param requestContext current request context
433 * @return attribute statement resulting from the query
435 * @throws ProfileException thrown if there is a problem making the query
437 protected AttributeStatement buildAttributeStatement(SAML2ProfileRequestContext requestContext)
438 throws ProfileException {
440 if (log.isDebugEnabled()) {
441 log.debug("Creating attribute statement in response to SAML request "
442 + requestContext.getSamlRequest().getID() + " from relying party "
443 + requestContext.getRelyingPartyId());
446 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
447 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
449 if (log.isDebugEnabled()) {
450 log.debug("Resolving principal name for subject of SAML request " + requestContext.getSamlRequest().getID()
451 + " from relying party " + requestContext.getRelyingPartyId());
455 if (log.isDebugEnabled()) {
456 log.debug("Resolving attributes for principal " + requestContext.getPrincipalName()
457 + " of SAML request " + requestContext.getSamlRequest().getID() + " from relying party "
458 + requestContext.getRelyingPartyId());
460 Map<String, BaseAttribute> principalAttributes = attributeAuthority
461 .getAttributes(buildAttributeRequestContext(requestContext));
463 requestContext.setPrincipalAttributes(principalAttributes);
465 if (requestContext.getSamlRequest() instanceof AttributeQuery) {
466 return attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext.getSamlRequest(),
467 principalAttributes.values());
469 return attributeAuthority.buildAttributeStatement(null, principalAttributes.values());
471 } catch (AttributeRequestException e) {
472 log.error("Error resolving attributes for SAML request " + requestContext.getSamlRequest().getID()
473 + " from relying party " + requestContext.getRelyingPartyId(), e);
474 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
475 throw new ProfileException("Error resolving attributes for SAML request "
476 + requestContext.getSamlRequest().getID() + " from relying party "
477 + requestContext.getRelyingPartyId(), e);
482 * Resolves the principal name of the subject of the request.
484 * @param requestContext current request context
486 * @throws ProfileException thrown if the principal name can not be resolved
488 protected void resolvePrincipal(SAML2ProfileRequestContext requestContext) throws ProfileException {
489 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
490 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
492 if (log.isDebugEnabled()) {
493 log.debug("Resolving principal name for subject of SAML request " + requestContext.getSamlRequest().getID()
494 + " from relying party " + requestContext.getRelyingPartyId());
498 String principal = attributeAuthority.getPrincipal(buildAttributeRequestContext(requestContext));
499 requestContext.setPrincipalName(principal);
500 } catch (AttributeRequestException e) {
501 log.error("Error resolving attributes for SAML request " + requestContext.getSamlRequest().getID()
502 + " from relying party " + requestContext.getRelyingPartyId(), e);
503 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.UNKNOWN_PRINCIPAL_URI,
504 "Error resolving principal"));
505 throw new ProfileException("Error resolving attributes for SAML request "
506 + requestContext.getSamlRequest().getID() + " from relying party "
507 + requestContext.getRelyingPartyId(), e);
512 * Creates an attribute query context from the current profile request context.
514 * @param requestContext current profile request
516 * @return created query context
518 protected ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery> buildAttributeRequestContext(
519 SAML2ProfileRequestContext requestContext) {
521 ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery> queryContext;
522 if (requestContext.getSamlRequest() instanceof AttributeQuery) {
523 queryContext = new ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery>(getMetadataProvider(),
524 requestContext.getRelyingPartyConfiguration(), (AttributeQuery) requestContext.getSamlRequest());
526 queryContext = new ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery>(getMetadataProvider(),
527 requestContext.getRelyingPartyConfiguration());
530 queryContext.setAttributeRequester(requestContext.getAssertingPartyId());
531 queryContext.setPrincipalName(requestContext.getPrincipalName());
532 queryContext.setProfileConfiguration(requestContext.getProfileConfiguration());
533 queryContext.setRequest(requestContext.getProfileRequest());
535 Session userSession = getSessionManager().getSession(getUserSessionId(requestContext.getProfileRequest()));
536 if (userSession != null) {
537 queryContext.setUserSession(userSession);
538 ServiceInformation serviceInfo = userSession.getServiceInformation(requestContext.getRelyingPartyId());
539 if (serviceInfo != null) {
540 String principalAuthenticationMethod = serviceInfo.getAuthenticationMethod().getAuthenticationMethod();
542 requestContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
543 queryContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
551 * Signs the given assertion if either the current profile configuration or the relying party configuration contains
552 * signing credentials.
554 * @param requestContext current request context
555 * @param assertion assertion to sign
557 * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
558 * required, if a signing credential is not configured
560 protected void signAssertion(SAML2ProfileRequestContext requestContext, Assertion assertion)
561 throws ProfileException {
562 if (log.isDebugEnabled()) {
563 log.debug("Determining if SAML assertion to relying party " + requestContext.getRelyingPartyId()
564 + " should be signed");
567 boolean signAssertion = false;
569 RoleDescriptor relyingPartyRole;
571 relyingPartyRole = getMetadataProvider().getRole(requestContext.getRelyingPartyId(),
572 requestContext.getRelyingPartyRole(), SAMLConstants.SAML20P_NS);
573 } catch (MetadataProviderException e) {
574 throw new ProfileException("Unable to lookup entity metadata for relying party "
575 + requestContext.getRelyingPartyId());
577 AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
579 if (relyingPartyRole instanceof SPSSODescriptor) {
580 SPSSODescriptor ssoDescriptor = (SPSSODescriptor) relyingPartyRole;
581 if (ssoDescriptor.getWantAssertionsSigned() != null) {
582 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
583 if (log.isDebugEnabled()) {
584 log.debug("Entity metadata for relying party " + requestContext.getRelyingPartyId()
585 + " indicates to sign assertions: " + signAssertion);
588 } else if (profileConfig.getSignAssertions()) {
589 signAssertion = true;
590 log.debug("IdP relying party configuration "
591 + requestContext.getRelyingPartyConfiguration().getRelyingPartyId()
592 + " indicates to sign assertions: " + signAssertion);
595 if (!signAssertion) {
599 if (log.isDebugEnabled()) {
600 log.debug("Determining signing credntial for assertion to relying party "
601 + requestContext.getRelyingPartyId());
603 Credential signatureCredential = profileConfig.getSigningCredential();
604 if (signatureCredential == null) {
605 signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
608 if (signatureCredential == null) {
609 throw new ProfileException("No signing credential is specified for relying party configuration "
610 + requestContext.getRelyingPartyConfiguration().getProviderId()
611 + " or it's SAML2 attribute query profile configuration");
614 if (log.isDebugEnabled()) {
615 log.debug("Signing assertion to relying party " + requestContext.getRelyingPartyId());
617 SAMLObjectContentReference contentRef = new SAMLObjectContentReference(assertion);
618 Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
619 signature.getContentReferences().add(contentRef);
620 assertion.setSignature(signature);
622 Signer.signObject(signature);
626 * Build a status message, with an optional second-level failure message.
628 * @param topLevelCode The top-level status code. Should be from saml-core-2.0-os, sec. 3.2.2.2
629 * @param secondLevelCode An optional second-level failure code. Should be from saml-core-2.0-is, sec 3.2.2.2. If
630 * null, no second-level Status element will be set.
631 * @param failureMessage An optional second-level failure message
633 * @return a Status object.
635 protected Status buildStatus(String topLevelCode, String secondLevelCode, String failureMessage) {
636 Status status = getStatusBuilder().buildObject();
638 StatusCode statusCode = getStatusCodeBuilder().buildObject();
639 statusCode.setValue(DatatypeHelper.safeTrimOrNullString(topLevelCode));
640 status.setStatusCode(statusCode);
642 if (secondLevelCode != null) {
643 StatusCode secondLevelStatusCode = getStatusCodeBuilder().buildObject();
644 secondLevelStatusCode.setValue(DatatypeHelper.safeTrimOrNullString(secondLevelCode));
645 statusCode.setStatusCode(secondLevelStatusCode);
648 if (failureMessage != null) {
649 StatusMessage msg = getStatusMessageBuilder().buildObject();
650 msg.setMessage(failureMessage);
651 status.setStatusMessage(msg);
658 * Builds the SAML subject for the user for the service provider.
660 * @param requestContext current request context
661 * @param confirmationMethod subject confirmation method used for the subject
663 * @return SAML subject for the user for the service provider
665 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
666 * name ID attribute or because there are no supported name formats
668 protected Subject buildSubject(SAML2ProfileRequestContext requestContext, String confirmationMethod)
669 throws ProfileException {
670 NameID nameID = buildNameId(requestContext);
671 requestContext.setSubjectNameID(nameID);
672 // TODO handle encryption
674 SubjectConfirmation subjectConfirmation = getSubjectConfirmationBuilder().buildObject();
675 subjectConfirmation.setMethod(confirmationMethod);
677 Subject subject = getSubjectBuilder().buildObject();
678 subject.setNameID(nameID);
679 subject.getSubjectConfirmations().add(subjectConfirmation);
685 * Builds a NameID appropriate for this request. NameIDs are built by inspecting the SAML request and metadata,
686 * picking a name format that was requested by the relying party or is mutually supported by both the relying party
687 * and asserting party as described in their metadata entries. Once a set of supported name formats is determined
688 * the principals attributes are inspected for an attribtue supported an attribute encoder whose category is one of
689 * the supported name formats.
691 * @param requestContext current request context
693 * @return the NameID appropriate for this request
695 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
696 * name ID attribute or because there are no supported name formats
698 protected NameID buildNameId(SAML2ProfileRequestContext requestContext) throws ProfileException {
699 if (log.isDebugEnabled()) {
700 log.debug("Building assertion NameID for principal/relying party:" + requestContext.getPrincipalName()
701 + "/" + requestContext.getRelyingPartyId());
703 Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
704 List<String> supportedNameFormats = getNameFormats(requestContext);
706 if (log.isDebugEnabled()) {
707 log.debug("Supported NameID formats: " + supportedNameFormats);
710 if (principalAttributes != null && supportedNameFormats != null) {
712 AttributeEncoder<NameID> nameIdEncoder = null;
713 for (BaseAttribute attribute : principalAttributes.values()) {
714 for (String nameFormat : supportedNameFormats) {
715 nameIdEncoder = attribute.getEncoderByCategory(nameFormat);
716 if (nameIdEncoder != null) {
717 if (log.isDebugEnabled()) {
718 log.debug("Using attribute " + attribute.getId() + " suppoting NameID format "
719 + nameFormat + " to create the NameID for principal "
720 + requestContext.getPrincipalName());
722 return nameIdEncoder.encode(attribute);
726 } catch (AttributeEncodingException e) {
727 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
728 "Unable to construct NameID"));
729 throw new ProfileException("Unable to encode NameID attribute", e);
733 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
734 "Unable to construct NameID"));
735 throw new ProfileException("No principal attributes support NameID construction");
739 * Gets the NameID format to use when creating NameIDs for the relying party.
741 * @param requestContext current request context
743 * @return list of nameID formats that may be used with the relying party
745 * @throws ProfileException thrown if there is a problem determing the NameID format to use
747 protected List<String> getNameFormats(SAML2ProfileRequestContext requestContext) throws ProfileException {
748 ArrayList<String> nameFormats = new ArrayList<String>();
751 RoleDescriptor assertingPartyRole = getMetadataProvider().getRole(requestContext.getAssertingPartyId(),
752 requestContext.getAssertingPartyRole(), SAMLConstants.SAML20P_NS);
753 List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
755 String nameFormat = null;
756 if (requestContext.getSamlRequest() instanceof AuthnRequest) {
757 AuthnRequest authnRequest = (AuthnRequest) requestContext.getSamlRequest();
758 if (authnRequest.getNameIDPolicy() != null) {
759 nameFormat = authnRequest.getNameIDPolicy().getFormat();
760 if (assertingPartySupportedFormats.contains(nameFormat)) {
761 nameFormats.add(nameFormat);
763 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
764 StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
765 throw new ProfileException("NameID format required by relying party is not supported");
770 if (nameFormats.isEmpty()) {
771 RoleDescriptor relyingPartyRole = getMetadataProvider().getRole(requestContext.getRelyingPartyId(),
772 requestContext.getRelyingPartyRole(), SAMLConstants.SAML20P_NS);
773 List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
775 assertingPartySupportedFormats.retainAll(relyingPartySupportedFormats);
776 nameFormats.addAll(assertingPartySupportedFormats);
778 if (nameFormats.isEmpty()) {
779 nameFormats.add("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
784 } catch (MetadataProviderException e) {
785 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
786 "Unable to lookup entity metadata"));
787 throw new ProfileException("Unable to determine lookup entity metadata", e);
792 * Gets the list of NameID formats supported for a given role.
794 * @param role the role to get the list of supported NameID formats
796 * @return list of supported NameID formats
798 protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
799 List<NameIDFormat> nameIDFormats = null;
801 if (role instanceof SSODescriptor) {
802 nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
803 } else if (role instanceof AuthnAuthorityDescriptor) {
804 nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
805 } else if (role instanceof PDPDescriptor) {
806 nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
807 } else if (role instanceof AttributeAuthorityDescriptor) {
808 nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
811 ArrayList<String> supportedFormats = new ArrayList<String>();
812 if (nameIDFormats != null) {
813 for (NameIDFormat format : nameIDFormats) {
814 supportedFormats.add(format.getFormat());
818 return supportedFormats;
822 * Constructs an SAML response message carrying a request error.
824 * @param requestContext current request context
826 * @return the constructed error response
828 protected Response buildErrorResponse(SAML2ProfileRequestContext requestContext) {
829 Response samlResponse = getResponseBuilder().buildObject();
830 samlResponse.setIssueInstant(new DateTime());
831 populateStatusResponse(requestContext, samlResponse);
833 samlResponse.setStatus(requestContext.getFailureStatus());
839 * Writes an aduit log entry indicating the successful response to the attribute request.
841 * @param context current request context
843 protected void writeAuditLogEntry(SAML2ProfileRequestContext context) {
844 AuditLogEntry auditLogEntry = new AuditLogEntry();
845 auditLogEntry.setMessageProfile(getProfileId());
846 auditLogEntry.setPrincipalAuthenticationMethod(context.getPrincipalAuthenticationMethod());
847 auditLogEntry.setPrincipalName(context.getPrincipalName());
848 auditLogEntry.setAssertingPartyId(context.getAssertingPartyId());
849 auditLogEntry.setRelyingPartyId(context.getRelyingPartyId());
850 auditLogEntry.setRequestBinding(context.getMessageDecoder().getBindingURI());
851 auditLogEntry.setRequestId(context.getSamlRequest().getID());
852 auditLogEntry.setResponseBinding(context.getMessageEncoder().getBindingURI());
853 auditLogEntry.setResponseId(context.getSamlResponse().getID());
854 getAduitLog().log(Level.CRITICAL, auditLogEntry);
858 * Contextual object used to accumlate information as profile requests are being processed.
860 * @param <RequestType> type of SAML 2 request
861 * @param <ResponseType> type of SAML 2 response
862 * @param <ProfileConfigurationType> configuration type for this profile
864 protected class SAML2ProfileRequestContext<RequestType extends RequestAbstractType, ResponseType extends StatusResponseType, ProfileConfigurationType extends AbstractSAML2ProfileConfiguration>
865 extends SAMLProfileRequestContext {
867 /** SAML request message. */
868 private RequestType samlRequest;
870 /** SAML response message. */
871 private ResponseType samlResponse;
873 /** Request profile configuration. */
874 private ProfileConfigurationType profileConfiguration;
876 /** The NameID of the subject of this request. */
877 private NameID subjectNameID;
879 /** The request failure status. */
880 private Status failureStatus;
885 * @param request current profile request
886 * @param response current profile response
888 public SAML2ProfileRequestContext(ProfileRequest<ServletRequest> request,
889 ProfileResponse<ServletResponse> response) {
890 super(request, response);
894 * Gets the NameID of the subject of this request.
896 * @return NameID of the subject of this request
898 public NameID getSubjectNameID() {
899 return subjectNameID;
903 * Sets the NameID of the subject of this request.
905 * @param nameID NameID of the subject of this request
907 public void setSubjectNameID(NameID nameID) {
908 subjectNameID = nameID;
912 * Gets the profile configuration for this request.
914 * @return profile configuration for this request
916 public ProfileConfigurationType getProfileConfiguration() {
917 return profileConfiguration;
921 * Sets the profile configuration for this request.
923 * @param configuration profile configuration for this request
925 public void setProfileConfiguration(ProfileConfigurationType configuration) {
926 profileConfiguration = configuration;
930 * Gets the SAML request message.
932 * @return SAML request message
934 public RequestType getSamlRequest() {
939 * Sets the SAML request message.
941 * @param request SAML request message
943 public void setSamlRequest(RequestType request) {
944 samlRequest = request;
948 * Gets the SAML response message.
950 * @return SAML response message
952 public ResponseType getSamlResponse() {
957 * Sets the SAML response message.
959 * @param response SAML response message
961 public void setSamlResponse(ResponseType response) {
962 samlResponse = response;
966 * Gets the status reflecting a request failure.
968 * @return status reflecting a request failure
970 public Status getFailureStatus() {
971 return failureStatus;
975 * Sets the status reflecting a request failure.
977 * @param status status reflecting a request failure
979 public void setFailureStatus(Status status) {
980 failureStatus = status;