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.log.Level;
33 import org.opensaml.saml2.core.Advice;
34 import org.opensaml.saml2.core.Assertion;
35 import org.opensaml.saml2.core.AttributeQuery;
36 import org.opensaml.saml2.core.AttributeStatement;
37 import org.opensaml.saml2.core.Audience;
38 import org.opensaml.saml2.core.AudienceRestriction;
39 import org.opensaml.saml2.core.AuthnRequest;
40 import org.opensaml.saml2.core.Conditions;
41 import org.opensaml.saml2.core.Issuer;
42 import org.opensaml.saml2.core.NameID;
43 import org.opensaml.saml2.core.ProxyRestriction;
44 import org.opensaml.saml2.core.RequestAbstractType;
45 import org.opensaml.saml2.core.Response;
46 import org.opensaml.saml2.core.Statement;
47 import org.opensaml.saml2.core.Status;
48 import org.opensaml.saml2.core.StatusCode;
49 import org.opensaml.saml2.core.StatusMessage;
50 import org.opensaml.saml2.core.StatusResponseType;
51 import org.opensaml.saml2.core.Subject;
52 import org.opensaml.saml2.core.SubjectConfirmation;
53 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
54 import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor;
55 import org.opensaml.saml2.metadata.NameIDFormat;
56 import org.opensaml.saml2.metadata.PDPDescriptor;
57 import org.opensaml.saml2.metadata.RoleDescriptor;
58 import org.opensaml.saml2.metadata.SPSSODescriptor;
59 import org.opensaml.saml2.metadata.SSODescriptor;
60 import org.opensaml.xml.XMLObjectBuilder;
61 import org.opensaml.xml.security.credential.Credential;
62 import org.opensaml.xml.signature.Signature;
63 import org.opensaml.xml.signature.Signer;
64 import org.opensaml.xml.util.DatatypeHelper;
66 import edu.internet2.middleware.shibboleth.common.attribute.AttributeRequestException;
67 import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
68 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncoder;
69 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncodingException;
70 import edu.internet2.middleware.shibboleth.common.attribute.encoding.SAML2NameIDAttributeEncoder;
71 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML2AttributeAuthority;
72 import edu.internet2.middleware.shibboleth.common.attribute.provider.ShibbolethSAMLAttributeRequestContext;
73 import edu.internet2.middleware.shibboleth.common.log.AuditLogEntry;
74 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
75 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
76 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
77 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AbstractSAML2ProfileConfiguration;
78 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
79 import edu.internet2.middleware.shibboleth.idp.session.ServiceInformation;
80 import edu.internet2.middleware.shibboleth.idp.session.Session;
82 /** Common implementation details for profile handlers. */
83 public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHandler {
85 /** SAML Version for this profile handler. */
86 public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_20;
89 private Logger log = Logger.getLogger(AbstractSAML2ProfileHandler.class);
91 /** For building response. */
92 private SAMLObjectBuilder<Response> responseBuilder;
94 /** For building status. */
95 private SAMLObjectBuilder<Status> statusBuilder;
97 /** For building statuscode. */
98 private SAMLObjectBuilder<StatusCode> statusCodeBuilder;
100 /** For building StatusMessages. */
101 private SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
103 /** For building assertion. */
104 private SAMLObjectBuilder<Assertion> assertionBuilder;
106 /** For building issuer. */
107 private SAMLObjectBuilder<Issuer> issuerBuilder;
109 /** For building subject. */
110 private SAMLObjectBuilder<Subject> subjectBuilder;
112 /** For builder subject confirmation. */
113 private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
115 /** For building conditions. */
116 private SAMLObjectBuilder<Conditions> conditionsBuilder;
118 /** For building audience restriction. */
119 private SAMLObjectBuilder<AudienceRestriction> audienceRestrictionBuilder;
121 /** For building proxy retrictions. */
122 private SAMLObjectBuilder<ProxyRestriction> proxyRestrictionBuilder;
124 /** For building audience. */
125 private SAMLObjectBuilder<Audience> audienceBuilder;
127 /** For building advice. */
128 private SAMLObjectBuilder<Advice> adviceBuilder;
130 /** For building signature. */
131 private XMLObjectBuilder<Signature> signatureBuilder;
134 @SuppressWarnings("unchecked")
135 protected AbstractSAML2ProfileHandler() {
138 responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
139 statusBuilder = (SAMLObjectBuilder<Status>) getBuilderFactory().getBuilder(Status.DEFAULT_ELEMENT_NAME);
140 statusCodeBuilder = (SAMLObjectBuilder<StatusCode>) getBuilderFactory().getBuilder(
141 StatusCode.DEFAULT_ELEMENT_NAME);
142 statusMessageBuilder = (SAMLObjectBuilder<StatusMessage>) getBuilderFactory().getBuilder(
143 StatusMessage.DEFAULT_ELEMENT_NAME);
144 issuerBuilder = (SAMLObjectBuilder<Issuer>) getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
145 assertionBuilder = (SAMLObjectBuilder<Assertion>) getBuilderFactory()
146 .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
147 subjectBuilder = (SAMLObjectBuilder<Subject>) getBuilderFactory().getBuilder(Subject.DEFAULT_ELEMENT_NAME);
148 subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) getBuilderFactory().getBuilder(
149 SubjectConfirmation.DEFAULT_ELEMENT_NAME);
150 conditionsBuilder = (SAMLObjectBuilder<Conditions>) getBuilderFactory().getBuilder(
151 Conditions.DEFAULT_ELEMENT_NAME);
152 audienceRestrictionBuilder = (SAMLObjectBuilder<AudienceRestriction>) getBuilderFactory().getBuilder(
153 AudienceRestriction.DEFAULT_ELEMENT_NAME);
154 proxyRestrictionBuilder = (SAMLObjectBuilder<ProxyRestriction>) getBuilderFactory().getBuilder(
155 ProxyRestriction.DEFAULT_ELEMENT_NAME);
156 audienceBuilder = (SAMLObjectBuilder<Audience>) getBuilderFactory().getBuilder(Audience.DEFAULT_ELEMENT_NAME);
157 adviceBuilder = (SAMLObjectBuilder<Advice>) getBuilderFactory().getBuilder(Advice.DEFAULT_ELEMENT_NAME);
158 signatureBuilder = (XMLObjectBuilder<Signature>) getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
162 * Convenience method for getting the SAML 2 advice builder.
164 * @return SAML 2 advice builder
166 public SAMLObjectBuilder<Advice> getAdviceBuilder() {
167 return adviceBuilder;
171 * Convenience method for getting the SAML 2 assertion builder.
173 * @return SAML 2 assertion builder
175 public SAMLObjectBuilder<Assertion> getAssertionBuilder() {
176 return assertionBuilder;
180 * Convenience method for getting the SAML 2 audience builder.
182 * @return SAML 2 audience builder
184 public SAMLObjectBuilder<Audience> getAudienceBuilder() {
185 return audienceBuilder;
189 * Convenience method for getting the SAML 2 audience restriction builder.
191 * @return SAML 2 audience restriction builder
193 public SAMLObjectBuilder<AudienceRestriction> getAudienceRestrictionBuilder() {
194 return audienceRestrictionBuilder;
198 * Convenience method for getting the SAML 2 conditions builder.
200 * @return SAML 2 conditions builder
202 public SAMLObjectBuilder<Conditions> getConditionsBuilder() {
203 return conditionsBuilder;
207 * Convenience method for getting the SAML 2 Issuer builder.
209 * @return SAML 2 Issuer builder
211 public SAMLObjectBuilder<Issuer> getIssuerBuilder() {
212 return issuerBuilder;
216 * Convenience method for getting the SAML 2 proxy restriction builder.
218 * @return SAML 2 proxy restriction builder
220 public SAMLObjectBuilder<ProxyRestriction> getProxyRestrictionBuilder() {
221 return proxyRestrictionBuilder;
225 * Convenience method for getting the SAML 2 response builder.
227 * @return SAML 2 response builder
229 public SAMLObjectBuilder<Response> getResponseBuilder() {
230 return responseBuilder;
234 * Convenience method for getting the Signature builder.
236 * @return signature builder
238 public XMLObjectBuilder<Signature> getSignatureBuilder() {
239 return signatureBuilder;
243 * Convenience method for getting the SAML 2 status builder.
245 * @return SAML 2 status builder
247 public SAMLObjectBuilder<Status> getStatusBuilder() {
248 return statusBuilder;
252 * Convenience method for getting the SAML 2 status code builder.
254 * @return SAML 2 status code builder
256 public SAMLObjectBuilder<StatusCode> getStatusCodeBuilder() {
257 return statusCodeBuilder;
261 * Convenience method for getting the SAML 2 status message builder.
263 * @return SAML 2 status message builder
265 public SAMLObjectBuilder<StatusMessage> getStatusMessageBuilder() {
266 return statusMessageBuilder;
270 * Convenience method for getting the SAML 2 subject builder.
272 * @return SAML 2 subject builder
274 public SAMLObjectBuilder<Subject> getSubjectBuilder() {
275 return subjectBuilder;
279 * Convenience method for getting the SAML 2 subject confirmation builder.
281 * @return SAML 2 subject confirmation builder
283 public SAMLObjectBuilder<SubjectConfirmation> getSubjectConfirmationBuilder() {
284 return subjectConfirmationBuilder;
288 * Checks that the SAML major version for a request is 2.
290 * @param requestContext current request context containing the SAML message
292 * @throws ProfileException thrown if the major version of the SAML request is not 2
294 protected void checkSamlVersion(SAML2ProfileRequestContext requestContext) throws ProfileException {
295 SAMLVersion version = requestContext.getSamlRequest().getVersion();
296 if (version.getMajorVersion() < 2) {
297 requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
298 StatusCode.REQUEST_VERSION_TOO_LOW_URI, null));
299 throw new ProfileException("SAML request version too low");
300 } else if (version.getMajorVersion() > 2) {
301 requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
302 StatusCode.REQUEST_VERSION_TOO_HIGH_URI, null));
303 throw new ProfileException("SAML request version too high");
308 * Builds a response to the attribute query within the request context.
310 * @param requestContext current request context
311 * @param assertionSubject subject of the assertion within the response
312 * @param statements the statements to include in the response
314 * @return the built response
316 * @throws ProfileException thrown if there is a problem creating the SAML response
318 protected Response buildResponse(SAML2ProfileRequestContext requestContext, Subject assertionSubject,
319 List<Statement> statements) throws ProfileException {
321 DateTime issueInstant = new DateTime();
323 // create the assertion and add the attribute statement
324 Assertion assertion = buildAssertion(requestContext, issueInstant);
325 assertion.setSubject(assertionSubject);
326 if (statements != null) {
327 assertion.getStatements().addAll(statements);
330 // create the SAML response and add the assertion
331 Response samlResponse = getResponseBuilder().buildObject();
332 samlResponse.setIssueInstant(issueInstant);
333 populateStatusResponse(requestContext, samlResponse);
335 samlResponse.getAssertions().add(assertion);
337 // sign the assertion if it should be signed
338 signAssertion(requestContext, assertion);
340 Status status = buildStatus(StatusCode.SUCCESS_URI, null, null);
341 samlResponse.setStatus(status);
347 * Builds a basic assertion with its id, issue instant, SAML version, issuer, subject, and conditions populated.
349 * @param requestContext current request context
350 * @param issueInstant time to use as assertion issue instant
352 * @return the built assertion
354 protected Assertion buildAssertion(SAML2ProfileRequestContext requestContext, DateTime issueInstant) {
355 Assertion assertion = getAssertionBuilder().buildObject();
356 assertion.setID(getIdGenerator().generateIdentifier());
357 assertion.setIssueInstant(issueInstant);
358 assertion.setVersion(SAMLVersion.VERSION_20);
359 assertion.setIssuer(buildEntityIssuer(requestContext));
361 Conditions conditions = buildConditions(requestContext, issueInstant);
362 assertion.setConditions(conditions);
368 * Creates an {@link Issuer} populated with information about the relying party.
370 * @param requestContext current request context
372 * @return the built issuer
374 protected Issuer buildEntityIssuer(SAML2ProfileRequestContext requestContext) {
375 Issuer issuer = getIssuerBuilder().buildObject();
376 issuer.setFormat(Issuer.ENTITY);
377 issuer.setValue(requestContext.getAssertingPartyId());
383 * Builds a SAML assertion condition set. The following fields are set; not before, not on or after, audience
384 * restrictions, and proxy restrictions.
386 * @param requestContext current request context
387 * @param issueInstant timestamp the assertion was created
389 * @return constructed conditions
391 protected Conditions buildConditions(SAML2ProfileRequestContext requestContext, DateTime issueInstant) {
392 AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
394 Conditions conditions = getConditionsBuilder().buildObject();
395 conditions.setNotBefore(issueInstant);
396 conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
398 Collection<String> audiences;
400 // add audience restrictions
401 audiences = profileConfig.getAssertionAudiences();
402 if (audiences != null && audiences.size() > 0) {
403 AudienceRestriction audienceRestriction = getAudienceRestrictionBuilder().buildObject();
404 for (String audienceUri : audiences) {
405 Audience audience = getAudienceBuilder().buildObject();
406 audience.setAudienceURI(audienceUri);
407 audienceRestriction.getAudiences().add(audience);
409 conditions.getAudienceRestrictions().add(audienceRestriction);
412 // add proxy restrictions
413 audiences = profileConfig.getProxyAudiences();
414 if (audiences != null && audiences.size() > 0) {
415 ProxyRestriction proxyRestriction = getProxyRestrictionBuilder().buildObject();
417 for (String audienceUri : audiences) {
418 audience = getAudienceBuilder().buildObject();
419 audience.setAudienceURI(audienceUri);
420 proxyRestriction.getAudiences().add(audience);
423 proxyRestriction.setProxyCount(profileConfig.getProxyCount());
424 conditions.getConditions().add(proxyRestriction);
431 * Populates the response's id, in response to, issue instant, version, and issuer properties.
433 * @param requestContext current request context
434 * @param response the response to populate
436 protected void populateStatusResponse(SAML2ProfileRequestContext requestContext, StatusResponseType response) {
437 response.setID(getIdGenerator().generateIdentifier());
438 if (requestContext.getSamlRequest() != null) {
439 response.setInResponseTo(requestContext.getSamlRequest().getID());
441 response.setVersion(SAMLVersion.VERSION_20);
442 response.setIssuer(buildEntityIssuer(requestContext));
446 * Executes a query for attributes and builds a SAML attribute statement from the results.
448 * @param requestContext current request context
450 * @return attribute statement resulting from the query
452 * @throws ProfileException thrown if there is a problem making the query
454 protected AttributeStatement buildAttributeStatement(SAML2ProfileRequestContext requestContext)
455 throws ProfileException {
457 if (log.isDebugEnabled()) {
458 log.debug("Creating attribute statement in response to SAML request "
459 + requestContext.getSamlRequest().getID() + " from relying party "
460 + requestContext.getRelyingPartyId());
463 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
464 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
467 if (log.isDebugEnabled()) {
468 log.debug("Resolving attributes for principal " + requestContext.getPrincipalName()
469 + " of SAML request " + requestContext.getSamlRequest().getID() + " from relying party "
470 + requestContext.getRelyingPartyId());
472 Map<String, BaseAttribute> principalAttributes = attributeAuthority
473 .getAttributes(buildAttributeRequestContext(requestContext));
475 requestContext.setPrincipalAttributes(principalAttributes);
477 if (requestContext.getSamlRequest() instanceof AttributeQuery) {
478 return attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext.getSamlRequest(),
479 principalAttributes.values());
481 return attributeAuthority.buildAttributeStatement(null, principalAttributes.values());
483 } catch (AttributeRequestException e) {
484 log.error("Error resolving attributes for SAML request " + requestContext.getSamlRequest().getID()
485 + " from relying party " + requestContext.getRelyingPartyId(), e);
486 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
487 throw new ProfileException("Error resolving attributes for SAML request "
488 + requestContext.getSamlRequest().getID() + " from relying party "
489 + requestContext.getRelyingPartyId(), e);
494 * Resolves the principal name of the subject of the request.
496 * @param requestContext current request context
498 * @throws ProfileException thrown if the principal name can not be resolved
500 protected void resolvePrincipal(SAML2ProfileRequestContext requestContext) throws ProfileException {
501 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
502 if (profileConfiguration == null) {
503 log.error("Unable to resolve principal, no SAML 2 profile configuration for relying party "
504 + requestContext.getRelyingPartyId());
505 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
506 "Error resolving principal"));
507 throw new ProfileException(
508 "Unable to resolve principal, no SAML 2 profile configuration for relying party "
509 + requestContext.getRelyingPartyId());
511 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
513 if (log.isDebugEnabled()) {
514 log.debug("Resolving principal name for subject of SAML request " + requestContext.getSamlRequest().getID()
515 + " from relying party " + requestContext.getRelyingPartyId());
519 String principal = attributeAuthority.getPrincipal(buildAttributeRequestContext(requestContext));
520 requestContext.setPrincipalName(principal);
521 } catch (AttributeRequestException e) {
522 log.error("Error resolving attributes for SAML request " + requestContext.getSamlRequest().getID()
523 + " from relying party " + requestContext.getRelyingPartyId(), e);
524 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.UNKNOWN_PRINCIPAL_URI,
525 "Error resolving principal"));
526 throw new ProfileException("Error resolving attributes for SAML request "
527 + requestContext.getSamlRequest().getID() + " from relying party "
528 + requestContext.getRelyingPartyId(), e);
533 * Creates an attribute query context from the current profile request context.
535 * @param requestContext current profile request
537 * @return created query context
539 protected ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery> buildAttributeRequestContext(
540 SAML2ProfileRequestContext requestContext) {
542 ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery> queryContext;
544 queryContext = new ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery>(getMetadataProvider(),
545 requestContext.getRelyingPartyConfiguration(), (AttributeQuery) requestContext.getSamlRequest());
546 queryContext.setAttributeRequester(requestContext.getAssertingPartyId());
547 queryContext.setPrincipalName(requestContext.getPrincipalName());
548 queryContext.setProfileConfiguration(requestContext.getProfileConfiguration());
549 queryContext.setRequest(requestContext.getProfileRequest());
551 Session userSession = getSessionManager().getSession(getUserSessionId(requestContext.getProfileRequest()));
552 if (userSession != null) {
553 queryContext.setUserSession(userSession);
554 ServiceInformation serviceInfo = userSession.getServicesInformation().get(
555 requestContext.getRelyingPartyId());
556 if (serviceInfo != null) {
557 String principalAuthenticationMethod = serviceInfo.getAuthenticationMethod().getAuthenticationMethod();
559 requestContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
560 queryContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
568 * Signs the given assertion if either the current profile configuration or the relying party configuration contains
569 * signing credentials.
571 * @param requestContext current request context
572 * @param assertion assertion to sign
574 * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
575 * required, if a signing credential is not configured
577 protected void signAssertion(SAML2ProfileRequestContext requestContext, Assertion assertion)
578 throws ProfileException {
579 if (log.isDebugEnabled()) {
580 log.debug("Determining if SAML assertion to relying party " + requestContext.getRelyingPartyId()
581 + " should be signed");
584 boolean signAssertion = false;
586 AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
588 if (requestContext.getRelyingPartyRoleMetadata() instanceof SPSSODescriptor) {
589 SPSSODescriptor ssoDescriptor = (SPSSODescriptor) requestContext.getRelyingPartyRoleMetadata();
590 if (ssoDescriptor.getWantAssertionsSigned() != null) {
591 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
592 if (log.isDebugEnabled()) {
593 log.debug("Entity metadata for relying party " + requestContext.getRelyingPartyId()
594 + " indicates to sign assertions: " + signAssertion);
597 } else if (profileConfig.getSignAssertions()) {
598 signAssertion = true;
599 log.debug("IdP relying party configuration "
600 + requestContext.getRelyingPartyConfiguration().getRelyingPartyId()
601 + " indicates to sign assertions: " + signAssertion);
604 if (!signAssertion) {
608 if (log.isDebugEnabled()) {
609 log.debug("Determining signing credntial for assertion to relying party "
610 + requestContext.getRelyingPartyId());
612 Credential signatureCredential = profileConfig.getSigningCredential();
613 if (signatureCredential == null) {
614 signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
617 if (signatureCredential == null) {
618 throw new ProfileException("No signing credential is specified for relying party configuration "
619 + requestContext.getRelyingPartyConfiguration().getProviderId()
620 + " or it's SAML2 attribute query profile configuration");
623 if (log.isDebugEnabled()) {
624 log.debug("Signing assertion to relying party " + requestContext.getRelyingPartyId());
626 SAMLObjectContentReference contentRef = new SAMLObjectContentReference(assertion);
627 Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
628 signature.getContentReferences().add(contentRef);
629 assertion.setSignature(signature);
631 Signer.signObject(signature);
635 * Build a status message, with an optional second-level failure message.
637 * @param topLevelCode The top-level status code. Should be from saml-core-2.0-os, sec. 3.2.2.2
638 * @param secondLevelCode An optional second-level failure code. Should be from saml-core-2.0-is, sec 3.2.2.2. If
639 * null, no second-level Status element will be set.
640 * @param failureMessage An optional second-level failure message
642 * @return a Status object.
644 protected Status buildStatus(String topLevelCode, String secondLevelCode, String failureMessage) {
645 Status status = getStatusBuilder().buildObject();
647 StatusCode statusCode = getStatusCodeBuilder().buildObject();
648 statusCode.setValue(DatatypeHelper.safeTrimOrNullString(topLevelCode));
649 status.setStatusCode(statusCode);
651 if (secondLevelCode != null) {
652 StatusCode secondLevelStatusCode = getStatusCodeBuilder().buildObject();
653 secondLevelStatusCode.setValue(DatatypeHelper.safeTrimOrNullString(secondLevelCode));
654 statusCode.setStatusCode(secondLevelStatusCode);
657 if (failureMessage != null) {
658 StatusMessage msg = getStatusMessageBuilder().buildObject();
659 msg.setMessage(failureMessage);
660 status.setStatusMessage(msg);
667 * Builds the SAML subject for the user for the service provider.
669 * @param requestContext current request context
670 * @param confirmationMethod subject confirmation method used for the subject
672 * @return SAML subject for the user for the service provider
674 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
675 * name ID attribute or because there are no supported name formats
677 protected Subject buildSubject(SAML2ProfileRequestContext requestContext, String confirmationMethod)
678 throws ProfileException {
679 NameID nameID = buildNameId(requestContext);
680 requestContext.setSubjectNameID(nameID);
681 // TODO handle encryption
683 SubjectConfirmation subjectConfirmation = getSubjectConfirmationBuilder().buildObject();
684 subjectConfirmation.setMethod(confirmationMethod);
686 Subject subject = getSubjectBuilder().buildObject();
687 subject.setNameID(nameID);
688 subject.getSubjectConfirmations().add(subjectConfirmation);
694 * Builds a NameID appropriate for this request. NameIDs are built by inspecting the SAML request and metadata,
695 * picking a name format that was requested by the relying party or is mutually supported by both the relying party
696 * and asserting party as described in their metadata entries. Once a set of supported name formats is determined
697 * the principals attributes are inspected for an attribute supported an attribute encoder whose category is one of
698 * the supported name formats.
700 * @param requestContext current request context
702 * @return the NameID appropriate for this request
704 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
705 * name ID attribute or because there are no supported name formats
707 protected NameID buildNameId(SAML2ProfileRequestContext requestContext) throws ProfileException {
708 if (log.isDebugEnabled()) {
709 log.debug("Building assertion NameID for principal/relying party:" + requestContext.getPrincipalName()
710 + "/" + requestContext.getRelyingPartyId());
712 Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
713 List<String> supportedNameFormats = getNameFormats(requestContext);
715 if (log.isDebugEnabled()) {
716 log.debug("Supported NameID formats: " + supportedNameFormats);
719 if (principalAttributes == null || supportedNameFormats == null) {
720 log.error("No attributes for principal " + requestContext.getPrincipalName()
721 + " support constructions of NameID");
722 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
723 "Unable to construct NameID"));
724 throw new ProfileException("No principal attributes support NameID construction");
728 SAML2NameIDAttributeEncoder nameIdEncoder;
729 for (BaseAttribute<?> attribute : principalAttributes.values()) {
730 for (AttributeEncoder encoder : attribute.getEncoders()) {
731 if (encoder instanceof SAML2NameIDAttributeEncoder) {
732 nameIdEncoder = (SAML2NameIDAttributeEncoder) encoder;
733 if (supportedNameFormats.contains(nameIdEncoder.getNameFormat())) {
734 if (log.isDebugEnabled()) {
735 log.debug("Using attribute " + attribute.getId() + " suppoting NameID format "
736 + nameIdEncoder.getNameFormat() + " to create the NameID for principal "
737 + requestContext.getPrincipalName());
739 return nameIdEncoder.encode(attribute);
744 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
745 throw new ProfileException("No principal attribute supported encoding into the a supported name ID format.");
746 } catch (AttributeEncodingException e) {
747 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
748 throw new ProfileException("Unable to encode NameID attribute", e);
753 * Gets the NameID format to use when creating NameIDs for the relying party.
755 * @param requestContext current request context
757 * @return list of nameID formats that may be used with the relying party
759 * @throws ProfileException thrown if there is a problem determing the NameID format to use
761 protected List<String> getNameFormats(SAML2ProfileRequestContext requestContext) throws ProfileException {
762 ArrayList<String> nameFormats = new ArrayList<String>();
764 List<String> assertingPartySupportedFormats = getEntitySupportedFormats(requestContext
765 .getAssertingPartyRoleMetadata());
767 String nameFormat = null;
768 if (requestContext.getSamlRequest() instanceof AuthnRequest) {
769 AuthnRequest authnRequest = (AuthnRequest) requestContext.getSamlRequest();
770 if (authnRequest.getNameIDPolicy() != null) {
771 nameFormat = authnRequest.getNameIDPolicy().getFormat();
772 if (assertingPartySupportedFormats.contains(nameFormat)) {
773 nameFormats.add(nameFormat);
775 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
776 StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
777 throw new ProfileException("NameID format required by relying party is not supported");
782 if (nameFormats.isEmpty()) {
783 List<String> relyingPartySupportedFormats = getEntitySupportedFormats(requestContext
784 .getRelyingPartyRoleMetadata());
786 assertingPartySupportedFormats.retainAll(relyingPartySupportedFormats);
787 nameFormats.addAll(assertingPartySupportedFormats);
789 if (nameFormats.isEmpty()) {
790 nameFormats.add("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
797 * Gets the list of NameID formats supported for a given role.
799 * @param role the role to get the list of supported NameID formats
801 * @return list of supported NameID formats
803 protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
804 List<NameIDFormat> nameIDFormats = null;
806 if (role instanceof SSODescriptor) {
807 nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
808 } else if (role instanceof AuthnAuthorityDescriptor) {
809 nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
810 } else if (role instanceof PDPDescriptor) {
811 nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
812 } else if (role instanceof AttributeAuthorityDescriptor) {
813 nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
816 ArrayList<String> supportedFormats = new ArrayList<String>();
817 if (nameIDFormats != null) {
818 for (NameIDFormat format : nameIDFormats) {
819 supportedFormats.add(format.getFormat());
823 return supportedFormats;
827 * Constructs an SAML response message carrying a request error.
829 * @param requestContext current request context
831 * @return the constructed error response
833 protected Response buildErrorResponse(SAML2ProfileRequestContext requestContext) {
834 Response samlResponse = getResponseBuilder().buildObject();
835 samlResponse.setIssueInstant(new DateTime());
836 populateStatusResponse(requestContext, samlResponse);
838 samlResponse.setStatus(requestContext.getFailureStatus());
844 * Writes an aduit log entry indicating the successful response to the attribute request.
846 * @param context current request context
848 protected void writeAuditLogEntry(SAML2ProfileRequestContext context) {
849 AuditLogEntry auditLogEntry = new AuditLogEntry();
850 auditLogEntry.setMessageProfile(getProfileId());
851 auditLogEntry.setPrincipalAuthenticationMethod(context.getPrincipalAuthenticationMethod());
852 auditLogEntry.setPrincipalName(context.getPrincipalName());
853 auditLogEntry.setAssertingPartyId(context.getAssertingPartyId());
854 auditLogEntry.setRelyingPartyId(context.getRelyingPartyId());
855 auditLogEntry.setRequestBinding(context.getMessageDecoder().getBindingURI());
856 auditLogEntry.setRequestId(context.getSamlRequest().getID());
857 auditLogEntry.setResponseBinding(context.getMessageEncoder().getBindingURI());
858 auditLogEntry.setResponseId(context.getSamlResponse().getID());
859 getAduitLog().log(Level.CRITICAL, auditLogEntry);
863 * Contextual object used to accumlate information as profile requests are being processed.
865 * @param <RequestType> type of SAML 2 request
866 * @param <ResponseType> type of SAML 2 response
867 * @param <ProfileConfigurationType> configuration type for this profile
869 protected class SAML2ProfileRequestContext<RequestType extends RequestAbstractType, ResponseType extends StatusResponseType, ProfileConfigurationType extends AbstractSAML2ProfileConfiguration>
870 extends SAMLProfileRequestContext {
872 /** SAML request message. */
873 private RequestType samlRequest;
875 /** SAML response message. */
876 private ResponseType samlResponse;
878 /** Request profile configuration. */
879 private ProfileConfigurationType profileConfiguration;
881 /** The NameID of the subject of this request. */
882 private NameID subjectNameID;
884 /** The request failure status. */
885 private Status failureStatus;
890 * @param request current profile request
891 * @param response current profile response
893 public SAML2ProfileRequestContext(ProfileRequest<ServletRequest> request,
894 ProfileResponse<ServletResponse> response) {
895 super(request, response);
899 * Gets the NameID of the subject of this request.
901 * @return NameID of the subject of this request
903 public NameID getSubjectNameID() {
904 return subjectNameID;
908 * Sets the NameID of the subject of this request.
910 * @param nameID NameID of the subject of this request
912 public void setSubjectNameID(NameID nameID) {
913 subjectNameID = nameID;
917 * Gets the profile configuration for this request.
919 * @return profile configuration for this request
921 public ProfileConfigurationType getProfileConfiguration() {
922 return profileConfiguration;
926 * Sets the profile configuration for this request.
928 * @param configuration profile configuration for this request
930 public void setProfileConfiguration(ProfileConfigurationType configuration) {
931 profileConfiguration = configuration;
935 * Gets the SAML request message.
937 * @return SAML request message
939 public RequestType getSamlRequest() {
944 * Sets the SAML request message.
946 * @param request SAML request message
948 public void setSamlRequest(RequestType request) {
949 samlRequest = request;
953 * Gets the SAML response message.
955 * @return SAML response message
957 public ResponseType getSamlResponse() {
962 * Sets the SAML response message.
964 * @param response SAML response message
966 public void setSamlResponse(ResponseType response) {
967 samlResponse = response;
971 * Gets the status reflecting a request failure.
973 * @return status reflecting a request failure
975 public Status getFailureStatus() {
976 return failureStatus;
980 * Sets the status reflecting a request failure.
982 * @param status status reflecting a request failure
984 public void setFailureStatus(Status status) {
985 failureStatus = status;