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.provider.SAML2AttributeAuthority;
71 import edu.internet2.middleware.shibboleth.common.attribute.provider.ShibbolethSAMLAttributeRequestContext;
72 import edu.internet2.middleware.shibboleth.common.log.AuditLogEntry;
73 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
74 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
75 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
76 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AbstractSAML2ProfileConfiguration;
77 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
78 import edu.internet2.middleware.shibboleth.idp.session.ServiceInformation;
79 import edu.internet2.middleware.shibboleth.idp.session.Session;
81 /** Common implementation details for profile handlers. */
82 public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHandler {
84 /** SAML Version for this profile handler. */
85 public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_20;
88 private Logger log = Logger.getLogger(AbstractSAML2ProfileHandler.class);
90 /** For building response. */
91 private SAMLObjectBuilder<Response> responseBuilder;
93 /** For building status. */
94 private SAMLObjectBuilder<Status> statusBuilder;
96 /** For building statuscode. */
97 private SAMLObjectBuilder<StatusCode> statusCodeBuilder;
99 /** For building StatusMessages. */
100 private SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
102 /** For building assertion. */
103 private SAMLObjectBuilder<Assertion> assertionBuilder;
105 /** For building issuer. */
106 private SAMLObjectBuilder<Issuer> issuerBuilder;
108 /** For building subject. */
109 private SAMLObjectBuilder<Subject> subjectBuilder;
111 /** For builder subject confirmation. */
112 private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
114 /** For building conditions. */
115 private SAMLObjectBuilder<Conditions> conditionsBuilder;
117 /** For building audience restriction. */
118 private SAMLObjectBuilder<AudienceRestriction> audienceRestrictionBuilder;
120 /** For building proxy retrictions. */
121 private SAMLObjectBuilder<ProxyRestriction> proxyRestrictionBuilder;
123 /** For building audience. */
124 private SAMLObjectBuilder<Audience> audienceBuilder;
126 /** For building advice. */
127 private SAMLObjectBuilder<Advice> adviceBuilder;
129 /** For building signature. */
130 private XMLObjectBuilder<Signature> signatureBuilder;
133 @SuppressWarnings("unchecked")
134 protected AbstractSAML2ProfileHandler() {
137 responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
138 statusBuilder = (SAMLObjectBuilder<Status>) getBuilderFactory().getBuilder(Status.DEFAULT_ELEMENT_NAME);
139 statusCodeBuilder = (SAMLObjectBuilder<StatusCode>) getBuilderFactory().getBuilder(
140 StatusCode.DEFAULT_ELEMENT_NAME);
141 statusMessageBuilder = (SAMLObjectBuilder<StatusMessage>) getBuilderFactory().getBuilder(
142 StatusMessage.DEFAULT_ELEMENT_NAME);
143 issuerBuilder = (SAMLObjectBuilder<Issuer>) getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
144 assertionBuilder = (SAMLObjectBuilder<Assertion>) getBuilderFactory()
145 .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
146 subjectBuilder = (SAMLObjectBuilder<Subject>) getBuilderFactory().getBuilder(Subject.DEFAULT_ELEMENT_NAME);
147 subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) getBuilderFactory().getBuilder(
148 SubjectConfirmation.DEFAULT_ELEMENT_NAME);
149 conditionsBuilder = (SAMLObjectBuilder<Conditions>) getBuilderFactory().getBuilder(
150 Conditions.DEFAULT_ELEMENT_NAME);
151 audienceRestrictionBuilder = (SAMLObjectBuilder<AudienceRestriction>) getBuilderFactory().getBuilder(
152 AudienceRestriction.DEFAULT_ELEMENT_NAME);
153 proxyRestrictionBuilder = (SAMLObjectBuilder<ProxyRestriction>) getBuilderFactory().getBuilder(
154 ProxyRestriction.DEFAULT_ELEMENT_NAME);
155 audienceBuilder = (SAMLObjectBuilder<Audience>) getBuilderFactory().getBuilder(Audience.DEFAULT_ELEMENT_NAME);
156 adviceBuilder = (SAMLObjectBuilder<Advice>) getBuilderFactory().getBuilder(Advice.DEFAULT_ELEMENT_NAME);
157 signatureBuilder = (XMLObjectBuilder<Signature>) getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
161 * Convenience method for getting the SAML 2 advice builder.
163 * @return SAML 2 advice builder
165 public SAMLObjectBuilder<Advice> getAdviceBuilder() {
166 return adviceBuilder;
170 * Convenience method for getting the SAML 2 assertion builder.
172 * @return SAML 2 assertion builder
174 public SAMLObjectBuilder<Assertion> getAssertionBuilder() {
175 return assertionBuilder;
179 * Convenience method for getting the SAML 2 audience builder.
181 * @return SAML 2 audience builder
183 public SAMLObjectBuilder<Audience> getAudienceBuilder() {
184 return audienceBuilder;
188 * Convenience method for getting the SAML 2 audience restriction builder.
190 * @return SAML 2 audience restriction builder
192 public SAMLObjectBuilder<AudienceRestriction> getAudienceRestrictionBuilder() {
193 return audienceRestrictionBuilder;
197 * Convenience method for getting the SAML 2 conditions builder.
199 * @return SAML 2 conditions builder
201 public SAMLObjectBuilder<Conditions> getConditionsBuilder() {
202 return conditionsBuilder;
206 * Convenience method for getting the SAML 2 Issuer builder.
208 * @return SAML 2 Issuer builder
210 public SAMLObjectBuilder<Issuer> getIssuerBuilder() {
211 return issuerBuilder;
215 * Convenience method for getting the SAML 2 proxy restriction builder.
217 * @return SAML 2 proxy restriction builder
219 public SAMLObjectBuilder<ProxyRestriction> getProxyRestrictionBuilder() {
220 return proxyRestrictionBuilder;
224 * Convenience method for getting the SAML 2 response builder.
226 * @return SAML 2 response builder
228 public SAMLObjectBuilder<Response> getResponseBuilder() {
229 return responseBuilder;
233 * Convenience method for getting the Signature builder.
235 * @return signature builder
237 public XMLObjectBuilder<Signature> getSignatureBuilder() {
238 return signatureBuilder;
242 * Convenience method for getting the SAML 2 status builder.
244 * @return SAML 2 status builder
246 public SAMLObjectBuilder<Status> getStatusBuilder() {
247 return statusBuilder;
251 * Convenience method for getting the SAML 2 status code builder.
253 * @return SAML 2 status code builder
255 public SAMLObjectBuilder<StatusCode> getStatusCodeBuilder() {
256 return statusCodeBuilder;
260 * Convenience method for getting the SAML 2 status message builder.
262 * @return SAML 2 status message builder
264 public SAMLObjectBuilder<StatusMessage> getStatusMessageBuilder() {
265 return statusMessageBuilder;
269 * Convenience method for getting the SAML 2 subject builder.
271 * @return SAML 2 subject builder
273 public SAMLObjectBuilder<Subject> getSubjectBuilder() {
274 return subjectBuilder;
278 * Convenience method for getting the SAML 2 subject confirmation builder.
280 * @return SAML 2 subject confirmation builder
282 public SAMLObjectBuilder<SubjectConfirmation> getSubjectConfirmationBuilder() {
283 return subjectConfirmationBuilder;
287 * Checks that the SAML major version for a request is 2.
289 * @param requestContext current request context containing the SAML message
291 * @throws ProfileException thrown if the major version of the SAML request is not 2
293 protected void checkSamlVersion(SAML2ProfileRequestContext requestContext) throws ProfileException {
294 SAMLVersion version = requestContext.getSamlRequest().getVersion();
295 if (version.getMajorVersion() < 2) {
296 requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
297 StatusCode.REQUEST_VERSION_TOO_LOW_URI, null));
298 throw new ProfileException("SAML request version too low");
299 } else if (version.getMajorVersion() > 2) {
300 requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
301 StatusCode.REQUEST_VERSION_TOO_HIGH_URI, null));
302 throw new ProfileException("SAML request version too high");
307 * Builds a response to the attribute query within the request context.
309 * @param requestContext current request context
310 * @param assertionSubject subject of the assertion within the response
311 * @param statements the statements to include in the response
313 * @return the built response
315 * @throws ProfileException thrown if there is a problem creating the SAML response
317 protected Response buildResponse(SAML2ProfileRequestContext requestContext, Subject assertionSubject,
318 List<Statement> statements) throws ProfileException {
320 DateTime issueInstant = new DateTime();
322 // create the assertion and add the attribute statement
323 Assertion assertion = buildAssertion(requestContext, issueInstant);
324 assertion.setSubject(assertionSubject);
325 if (statements != null) {
326 assertion.getStatements().addAll(statements);
329 // create the SAML response and add the assertion
330 Response samlResponse = getResponseBuilder().buildObject();
331 samlResponse.setIssueInstant(issueInstant);
332 populateStatusResponse(requestContext, samlResponse);
334 samlResponse.getAssertions().add(assertion);
336 // sign the assertion if it should be signed
337 signAssertion(requestContext, assertion);
339 Status status = buildStatus(StatusCode.SUCCESS_URI, null, null);
340 samlResponse.setStatus(status);
346 * Builds a basic assertion with its id, issue instant, SAML version, issuer, subject, and conditions populated.
348 * @param requestContext current request context
349 * @param issueInstant time to use as assertion issue instant
351 * @return the built assertion
353 protected Assertion buildAssertion(SAML2ProfileRequestContext requestContext, DateTime issueInstant) {
354 Assertion assertion = getAssertionBuilder().buildObject();
355 assertion.setID(getIdGenerator().generateIdentifier());
356 assertion.setIssueInstant(issueInstant);
357 assertion.setVersion(SAMLVersion.VERSION_20);
358 assertion.setIssuer(buildEntityIssuer(requestContext));
360 Conditions conditions = buildConditions(requestContext, issueInstant);
361 assertion.setConditions(conditions);
367 * Creates an {@link Issuer} populated with information about the relying party.
369 * @param requestContext current request context
371 * @return the built issuer
373 protected Issuer buildEntityIssuer(SAML2ProfileRequestContext requestContext) {
374 Issuer issuer = getIssuerBuilder().buildObject();
375 issuer.setFormat(Issuer.ENTITY);
376 issuer.setValue(requestContext.getAssertingPartyId());
382 * Builds a SAML assertion condition set. The following fields are set; not before, not on or after, audience
383 * restrictions, and proxy restrictions.
385 * @param requestContext current request context
386 * @param issueInstant timestamp the assertion was created
388 * @return constructed conditions
390 protected Conditions buildConditions(SAML2ProfileRequestContext requestContext, DateTime issueInstant) {
391 AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
393 Conditions conditions = getConditionsBuilder().buildObject();
394 conditions.setNotBefore(issueInstant);
395 conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
397 Collection<String> audiences;
399 // add audience restrictions
400 audiences = profileConfig.getAssertionAudiences();
401 if (audiences != null && audiences.size() > 0) {
402 AudienceRestriction audienceRestriction = getAudienceRestrictionBuilder().buildObject();
403 for (String audienceUri : audiences) {
404 Audience audience = getAudienceBuilder().buildObject();
405 audience.setAudienceURI(audienceUri);
406 audienceRestriction.getAudiences().add(audience);
408 conditions.getAudienceRestrictions().add(audienceRestriction);
411 // add proxy restrictions
412 audiences = profileConfig.getProxyAudiences();
413 if (audiences != null && audiences.size() > 0) {
414 ProxyRestriction proxyRestriction = getProxyRestrictionBuilder().buildObject();
416 for (String audienceUri : audiences) {
417 audience = getAudienceBuilder().buildObject();
418 audience.setAudienceURI(audienceUri);
419 proxyRestriction.getAudiences().add(audience);
422 proxyRestriction.setProxyCount(profileConfig.getProxyCount());
423 conditions.getConditions().add(proxyRestriction);
430 * Populates the response's id, in response to, issue instant, version, and issuer properties.
432 * @param requestContext current request context
433 * @param response the response to populate
435 protected void populateStatusResponse(SAML2ProfileRequestContext requestContext, StatusResponseType response) {
436 response.setID(getIdGenerator().generateIdentifier());
437 if (requestContext.getSamlRequest() != null) {
438 response.setInResponseTo(requestContext.getSamlRequest().getID());
440 response.setVersion(SAMLVersion.VERSION_20);
441 response.setIssuer(buildEntityIssuer(requestContext));
445 * Executes a query for attributes and builds a SAML attribute statement from the results.
447 * @param requestContext current request context
449 * @return attribute statement resulting from the query
451 * @throws ProfileException thrown if there is a problem making the query
453 protected AttributeStatement buildAttributeStatement(SAML2ProfileRequestContext requestContext)
454 throws ProfileException {
456 if (log.isDebugEnabled()) {
457 log.debug("Creating attribute statement in response to SAML request "
458 + requestContext.getSamlRequest().getID() + " from relying party "
459 + requestContext.getRelyingPartyId());
462 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
463 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
466 if (log.isDebugEnabled()) {
467 log.debug("Resolving attributes for principal " + requestContext.getPrincipalName()
468 + " of SAML request " + requestContext.getSamlRequest().getID() + " from relying party "
469 + requestContext.getRelyingPartyId());
471 Map<String, BaseAttribute> principalAttributes = attributeAuthority
472 .getAttributes(buildAttributeRequestContext(requestContext));
474 requestContext.setPrincipalAttributes(principalAttributes);
476 if (requestContext.getSamlRequest() instanceof AttributeQuery) {
477 return attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext.getSamlRequest(),
478 principalAttributes.values());
480 return attributeAuthority.buildAttributeStatement(null, principalAttributes.values());
482 } catch (AttributeRequestException e) {
483 log.error("Error resolving attributes for SAML request " + requestContext.getSamlRequest().getID()
484 + " from relying party " + requestContext.getRelyingPartyId(), e);
485 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
486 throw new ProfileException("Error resolving attributes for SAML request "
487 + requestContext.getSamlRequest().getID() + " from relying party "
488 + requestContext.getRelyingPartyId(), e);
493 * Resolves the principal name of the subject of the request.
495 * @param requestContext current request context
497 * @throws ProfileException thrown if the principal name can not be resolved
499 protected void resolvePrincipal(SAML2ProfileRequestContext requestContext) throws ProfileException {
500 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
501 if (profileConfiguration == null) {
502 log.error("Unable to resolve principal, no SAML 2 profile configuration for relying party "
503 + requestContext.getRelyingPartyId());
504 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
505 "Error resolving principal"));
506 throw new ProfileException(
507 "Unable to resolve principal, no SAML 2 profile configuration for relying party "
508 + requestContext.getRelyingPartyId());
510 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
512 if (log.isDebugEnabled()) {
513 log.debug("Resolving principal name for subject of SAML request " + requestContext.getSamlRequest().getID()
514 + " from relying party " + requestContext.getRelyingPartyId());
518 String principal = attributeAuthority.getPrincipal(buildAttributeRequestContext(requestContext));
519 requestContext.setPrincipalName(principal);
520 } catch (AttributeRequestException e) {
521 log.error("Error resolving attributes for SAML request " + requestContext.getSamlRequest().getID()
522 + " from relying party " + requestContext.getRelyingPartyId(), e);
523 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.UNKNOWN_PRINCIPAL_URI,
524 "Error resolving principal"));
525 throw new ProfileException("Error resolving attributes for SAML request "
526 + requestContext.getSamlRequest().getID() + " from relying party "
527 + requestContext.getRelyingPartyId(), e);
532 * Creates an attribute query context from the current profile request context.
534 * @param requestContext current profile request
536 * @return created query context
538 protected ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery> buildAttributeRequestContext(
539 SAML2ProfileRequestContext requestContext) {
541 ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery> queryContext;
543 queryContext = new ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery>(getMetadataProvider(),
544 requestContext.getRelyingPartyConfiguration(), (AttributeQuery) requestContext.getSamlRequest());
545 queryContext.setAttributeRequester(requestContext.getAssertingPartyId());
546 queryContext.setPrincipalName(requestContext.getPrincipalName());
547 queryContext.setProfileConfiguration(requestContext.getProfileConfiguration());
548 queryContext.setRequest(requestContext.getProfileRequest());
550 Session userSession = getSessionManager().getSession(getUserSessionId(requestContext.getProfileRequest()));
551 if (userSession != null) {
552 queryContext.setUserSession(userSession);
553 ServiceInformation serviceInfo = userSession.getServicesInformation().get(
554 requestContext.getRelyingPartyId());
555 if (serviceInfo != null) {
556 String principalAuthenticationMethod = serviceInfo.getAuthenticationMethod().getAuthenticationMethod();
558 requestContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
559 queryContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
567 * Signs the given assertion if either the current profile configuration or the relying party configuration contains
568 * signing credentials.
570 * @param requestContext current request context
571 * @param assertion assertion to sign
573 * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
574 * required, if a signing credential is not configured
576 protected void signAssertion(SAML2ProfileRequestContext requestContext, Assertion assertion)
577 throws ProfileException {
578 if (log.isDebugEnabled()) {
579 log.debug("Determining if SAML assertion to relying party " + requestContext.getRelyingPartyId()
580 + " should be signed");
583 boolean signAssertion = false;
585 AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
587 if (requestContext.getRelyingPartyRoleMetadata() instanceof SPSSODescriptor) {
588 SPSSODescriptor ssoDescriptor = (SPSSODescriptor) requestContext.getRelyingPartyRoleMetadata();
589 if (ssoDescriptor.getWantAssertionsSigned() != null) {
590 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
591 if (log.isDebugEnabled()) {
592 log.debug("Entity metadata for relying party " + requestContext.getRelyingPartyId()
593 + " indicates to sign assertions: " + signAssertion);
596 } else if (profileConfig.getSignAssertions()) {
597 signAssertion = true;
598 log.debug("IdP relying party configuration "
599 + requestContext.getRelyingPartyConfiguration().getRelyingPartyId()
600 + " indicates to sign assertions: " + signAssertion);
603 if (!signAssertion) {
607 if (log.isDebugEnabled()) {
608 log.debug("Determining signing credntial for assertion to relying party "
609 + requestContext.getRelyingPartyId());
611 Credential signatureCredential = profileConfig.getSigningCredential();
612 if (signatureCredential == null) {
613 signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
616 if (signatureCredential == null) {
617 throw new ProfileException("No signing credential is specified for relying party configuration "
618 + requestContext.getRelyingPartyConfiguration().getProviderId()
619 + " or it's SAML2 attribute query profile configuration");
622 if (log.isDebugEnabled()) {
623 log.debug("Signing assertion to relying party " + requestContext.getRelyingPartyId());
625 SAMLObjectContentReference contentRef = new SAMLObjectContentReference(assertion);
626 Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
627 signature.getContentReferences().add(contentRef);
628 assertion.setSignature(signature);
630 Signer.signObject(signature);
634 * Build a status message, with an optional second-level failure message.
636 * @param topLevelCode The top-level status code. Should be from saml-core-2.0-os, sec. 3.2.2.2
637 * @param secondLevelCode An optional second-level failure code. Should be from saml-core-2.0-is, sec 3.2.2.2. If
638 * null, no second-level Status element will be set.
639 * @param failureMessage An optional second-level failure message
641 * @return a Status object.
643 protected Status buildStatus(String topLevelCode, String secondLevelCode, String failureMessage) {
644 Status status = getStatusBuilder().buildObject();
646 StatusCode statusCode = getStatusCodeBuilder().buildObject();
647 statusCode.setValue(DatatypeHelper.safeTrimOrNullString(topLevelCode));
648 status.setStatusCode(statusCode);
650 if (secondLevelCode != null) {
651 StatusCode secondLevelStatusCode = getStatusCodeBuilder().buildObject();
652 secondLevelStatusCode.setValue(DatatypeHelper.safeTrimOrNullString(secondLevelCode));
653 statusCode.setStatusCode(secondLevelStatusCode);
656 if (failureMessage != null) {
657 StatusMessage msg = getStatusMessageBuilder().buildObject();
658 msg.setMessage(failureMessage);
659 status.setStatusMessage(msg);
666 * Builds the SAML subject for the user for the service provider.
668 * @param requestContext current request context
669 * @param confirmationMethod subject confirmation method used for the subject
671 * @return SAML subject for the user for the service provider
673 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
674 * name ID attribute or because there are no supported name formats
676 protected Subject buildSubject(SAML2ProfileRequestContext requestContext, String confirmationMethod)
677 throws ProfileException {
678 NameID nameID = buildNameId(requestContext);
679 requestContext.setSubjectNameID(nameID);
680 // TODO handle encryption
682 SubjectConfirmation subjectConfirmation = getSubjectConfirmationBuilder().buildObject();
683 subjectConfirmation.setMethod(confirmationMethod);
685 Subject subject = getSubjectBuilder().buildObject();
686 subject.setNameID(nameID);
687 subject.getSubjectConfirmations().add(subjectConfirmation);
693 * Builds a NameID appropriate for this request. NameIDs are built by inspecting the SAML request and metadata,
694 * picking a name format that was requested by the relying party or is mutually supported by both the relying party
695 * and asserting party as described in their metadata entries. Once a set of supported name formats is determined
696 * the principals attributes are inspected for an attribute supported an attribute encoder whose category is one of
697 * the supported name formats.
699 * @param requestContext current request context
701 * @return the NameID appropriate for this request
703 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
704 * name ID attribute or because there are no supported name formats
706 protected NameID buildNameId(SAML2ProfileRequestContext requestContext) throws ProfileException {
707 if (log.isDebugEnabled()) {
708 log.debug("Building assertion NameID for principal/relying party:" + requestContext.getPrincipalName()
709 + "/" + requestContext.getRelyingPartyId());
711 Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
712 List<String> supportedNameFormats = getNameFormats(requestContext);
714 if (log.isDebugEnabled()) {
715 log.debug("Supported NameID formats: " + supportedNameFormats);
718 if (principalAttributes != null && supportedNameFormats != null) {
720 AttributeEncoder<NameID> nameIdEncoder = null;
721 for (BaseAttribute attribute : principalAttributes.values()) {
722 for (String nameFormat : supportedNameFormats) {
723 nameIdEncoder = attribute.getEncoderByCategory(nameFormat);
724 if (nameIdEncoder != null) {
725 if (log.isDebugEnabled()) {
726 log.debug("Using attribute " + attribute.getId() + " suppoting NameID format "
727 + nameFormat + " to create the NameID for principal "
728 + requestContext.getPrincipalName());
730 return nameIdEncoder.encode(attribute);
734 } catch (AttributeEncodingException e) {
735 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
736 "Unable to construct NameID"));
737 throw new ProfileException("Unable to encode NameID attribute", e);
741 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
742 "Unable to construct NameID"));
743 throw new ProfileException("No principal attributes support NameID construction");
747 * Gets the NameID format to use when creating NameIDs for the relying party.
749 * @param requestContext current request context
751 * @return list of nameID formats that may be used with the relying party
753 * @throws ProfileException thrown if there is a problem determing the NameID format to use
755 protected List<String> getNameFormats(SAML2ProfileRequestContext requestContext) throws ProfileException {
756 ArrayList<String> nameFormats = new ArrayList<String>();
758 List<String> assertingPartySupportedFormats = getEntitySupportedFormats(requestContext
759 .getAssertingPartyRoleMetadata());
761 String nameFormat = null;
762 if (requestContext.getSamlRequest() instanceof AuthnRequest) {
763 AuthnRequest authnRequest = (AuthnRequest) requestContext.getSamlRequest();
764 if (authnRequest.getNameIDPolicy() != null) {
765 nameFormat = authnRequest.getNameIDPolicy().getFormat();
766 if (assertingPartySupportedFormats.contains(nameFormat)) {
767 nameFormats.add(nameFormat);
769 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
770 StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
771 throw new ProfileException("NameID format required by relying party is not supported");
776 if (nameFormats.isEmpty()) {
777 List<String> relyingPartySupportedFormats = getEntitySupportedFormats(requestContext
778 .getRelyingPartyRoleMetadata());
780 assertingPartySupportedFormats.retainAll(relyingPartySupportedFormats);
781 nameFormats.addAll(assertingPartySupportedFormats);
783 if (nameFormats.isEmpty()) {
784 nameFormats.add("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
791 * Gets the list of NameID formats supported for a given role.
793 * @param role the role to get the list of supported NameID formats
795 * @return list of supported NameID formats
797 protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
798 List<NameIDFormat> nameIDFormats = null;
800 if (role instanceof SSODescriptor) {
801 nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
802 } else if (role instanceof AuthnAuthorityDescriptor) {
803 nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
804 } else if (role instanceof PDPDescriptor) {
805 nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
806 } else if (role instanceof AttributeAuthorityDescriptor) {
807 nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
810 ArrayList<String> supportedFormats = new ArrayList<String>();
811 if (nameIDFormats != null) {
812 for (NameIDFormat format : nameIDFormats) {
813 supportedFormats.add(format.getFormat());
817 return supportedFormats;
821 * Constructs an SAML response message carrying a request error.
823 * @param requestContext current request context
825 * @return the constructed error response
827 protected Response buildErrorResponse(SAML2ProfileRequestContext requestContext) {
828 Response samlResponse = getResponseBuilder().buildObject();
829 samlResponse.setIssueInstant(new DateTime());
830 populateStatusResponse(requestContext, samlResponse);
832 samlResponse.setStatus(requestContext.getFailureStatus());
838 * Writes an aduit log entry indicating the successful response to the attribute request.
840 * @param context current request context
842 protected void writeAuditLogEntry(SAML2ProfileRequestContext context) {
843 AuditLogEntry auditLogEntry = new AuditLogEntry();
844 auditLogEntry.setMessageProfile(getProfileId());
845 auditLogEntry.setPrincipalAuthenticationMethod(context.getPrincipalAuthenticationMethod());
846 auditLogEntry.setPrincipalName(context.getPrincipalName());
847 auditLogEntry.setAssertingPartyId(context.getAssertingPartyId());
848 auditLogEntry.setRelyingPartyId(context.getRelyingPartyId());
849 auditLogEntry.setRequestBinding(context.getMessageDecoder().getBindingURI());
850 auditLogEntry.setRequestId(context.getSamlRequest().getID());
851 auditLogEntry.setResponseBinding(context.getMessageEncoder().getBindingURI());
852 auditLogEntry.setResponseId(context.getSamlResponse().getID());
853 getAduitLog().log(Level.CRITICAL, auditLogEntry);
857 * Contextual object used to accumlate information as profile requests are being processed.
859 * @param <RequestType> type of SAML 2 request
860 * @param <ResponseType> type of SAML 2 response
861 * @param <ProfileConfigurationType> configuration type for this profile
863 protected class SAML2ProfileRequestContext<RequestType extends RequestAbstractType, ResponseType extends StatusResponseType, ProfileConfigurationType extends AbstractSAML2ProfileConfiguration>
864 extends SAMLProfileRequestContext {
866 /** SAML request message. */
867 private RequestType samlRequest;
869 /** SAML response message. */
870 private ResponseType samlResponse;
872 /** Request profile configuration. */
873 private ProfileConfigurationType profileConfiguration;
875 /** The NameID of the subject of this request. */
876 private NameID subjectNameID;
878 /** The request failure status. */
879 private Status failureStatus;
884 * @param request current profile request
885 * @param response current profile response
887 public SAML2ProfileRequestContext(ProfileRequest<ServletRequest> request,
888 ProfileResponse<ServletResponse> response) {
889 super(request, response);
893 * Gets the NameID of the subject of this request.
895 * @return NameID of the subject of this request
897 public NameID getSubjectNameID() {
898 return subjectNameID;
902 * Sets the NameID of the subject of this request.
904 * @param nameID NameID of the subject of this request
906 public void setSubjectNameID(NameID nameID) {
907 subjectNameID = nameID;
911 * Gets the profile configuration for this request.
913 * @return profile configuration for this request
915 public ProfileConfigurationType getProfileConfiguration() {
916 return profileConfiguration;
920 * Sets the profile configuration for this request.
922 * @param configuration profile configuration for this request
924 public void setProfileConfiguration(ProfileConfigurationType configuration) {
925 profileConfiguration = configuration;
929 * Gets the SAML request message.
931 * @return SAML request message
933 public RequestType getSamlRequest() {
938 * Sets the SAML request message.
940 * @param request SAML request message
942 public void setSamlRequest(RequestType request) {
943 samlRequest = request;
947 * Gets the SAML response message.
949 * @return SAML response message
951 public ResponseType getSamlResponse() {
956 * Sets the SAML response message.
958 * @param response SAML response message
960 public void setSamlResponse(ResponseType response) {
961 samlResponse = response;
965 * Gets the status reflecting a request failure.
967 * @return status reflecting a request failure
969 public Status getFailureStatus() {
970 return failureStatus;
974 * Sets the status reflecting a request failure.
976 * @param status status reflecting a request failure
978 public void setFailureStatus(Status status) {
979 failureStatus = status;