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 org.joda.time.DateTime;
25 import org.opensaml.Configuration;
26 import org.opensaml.common.SAMLObjectBuilder;
27 import org.opensaml.common.SAMLVersion;
28 import org.opensaml.saml2.core.Assertion;
29 import org.opensaml.saml2.core.AttributeQuery;
30 import org.opensaml.saml2.core.AttributeStatement;
31 import org.opensaml.saml2.core.Audience;
32 import org.opensaml.saml2.core.AudienceRestriction;
33 import org.opensaml.saml2.core.AuthnRequest;
34 import org.opensaml.saml2.core.Conditions;
35 import org.opensaml.saml2.core.Issuer;
36 import org.opensaml.saml2.core.NameID;
37 import org.opensaml.saml2.core.ProxyRestriction;
38 import org.opensaml.saml2.core.Response;
39 import org.opensaml.saml2.core.Statement;
40 import org.opensaml.saml2.core.Status;
41 import org.opensaml.saml2.core.StatusCode;
42 import org.opensaml.saml2.core.StatusMessage;
43 import org.opensaml.saml2.core.StatusResponseType;
44 import org.opensaml.saml2.core.Subject;
45 import org.opensaml.saml2.core.SubjectConfirmation;
46 import org.opensaml.saml2.core.SubjectConfirmationData;
47 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
48 import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor;
49 import org.opensaml.saml2.metadata.Endpoint;
50 import org.opensaml.saml2.metadata.NameIDFormat;
51 import org.opensaml.saml2.metadata.PDPDescriptor;
52 import org.opensaml.saml2.metadata.RoleDescriptor;
53 import org.opensaml.saml2.metadata.SPSSODescriptor;
54 import org.opensaml.saml2.metadata.SSODescriptor;
55 import org.opensaml.ws.transport.http.HTTPInTransport;
56 import org.opensaml.xml.XMLObjectBuilder;
57 import org.opensaml.xml.io.Marshaller;
58 import org.opensaml.xml.io.MarshallingException;
59 import org.opensaml.xml.security.SecurityException;
60 import org.opensaml.xml.security.SecurityHelper;
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;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
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.encoding.SAML2NameIDAttributeEncoder;
73 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML2AttributeAuthority;
74 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
75 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AbstractSAML2ProfileConfiguration;
76 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
78 /** Common implementation details for profile handlers. */
79 public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHandler {
81 /** SAML Version for this profile handler. */
82 public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_20;
85 private Logger log = LoggerFactory.getLogger(AbstractSAML2ProfileHandler.class);
87 /** For building response. */
88 private SAMLObjectBuilder<Response> responseBuilder;
90 /** For building status. */
91 private SAMLObjectBuilder<Status> statusBuilder;
93 /** For building statuscode. */
94 private SAMLObjectBuilder<StatusCode> statusCodeBuilder;
96 /** For building StatusMessages. */
97 private SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
99 /** For building assertion. */
100 private SAMLObjectBuilder<Assertion> assertionBuilder;
102 /** For building issuer. */
103 private SAMLObjectBuilder<Issuer> issuerBuilder;
105 /** For building subject. */
106 private SAMLObjectBuilder<Subject> subjectBuilder;
108 /** For building subject confirmation. */
109 private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
111 /** For building subject confirmation data. */
112 private SAMLObjectBuilder<SubjectConfirmationData> subjectConfirmationDataBuilder;
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 signature. */
127 private XMLObjectBuilder<Signature> signatureBuilder;
130 @SuppressWarnings("unchecked")
131 protected AbstractSAML2ProfileHandler() {
134 responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
135 statusBuilder = (SAMLObjectBuilder<Status>) getBuilderFactory().getBuilder(Status.DEFAULT_ELEMENT_NAME);
136 statusCodeBuilder = (SAMLObjectBuilder<StatusCode>) getBuilderFactory().getBuilder(
137 StatusCode.DEFAULT_ELEMENT_NAME);
138 statusMessageBuilder = (SAMLObjectBuilder<StatusMessage>) getBuilderFactory().getBuilder(
139 StatusMessage.DEFAULT_ELEMENT_NAME);
140 issuerBuilder = (SAMLObjectBuilder<Issuer>) getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
141 assertionBuilder = (SAMLObjectBuilder<Assertion>) getBuilderFactory()
142 .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
143 subjectBuilder = (SAMLObjectBuilder<Subject>) getBuilderFactory().getBuilder(Subject.DEFAULT_ELEMENT_NAME);
144 subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) getBuilderFactory().getBuilder(
145 SubjectConfirmation.DEFAULT_ELEMENT_NAME);
146 subjectConfirmationDataBuilder = (SAMLObjectBuilder<SubjectConfirmationData>) getBuilderFactory().getBuilder(
147 SubjectConfirmationData.DEFAULT_ELEMENT_NAME);
148 conditionsBuilder = (SAMLObjectBuilder<Conditions>) getBuilderFactory().getBuilder(
149 Conditions.DEFAULT_ELEMENT_NAME);
150 audienceRestrictionBuilder = (SAMLObjectBuilder<AudienceRestriction>) getBuilderFactory().getBuilder(
151 AudienceRestriction.DEFAULT_ELEMENT_NAME);
152 proxyRestrictionBuilder = (SAMLObjectBuilder<ProxyRestriction>) getBuilderFactory().getBuilder(
153 ProxyRestriction.DEFAULT_ELEMENT_NAME);
154 audienceBuilder = (SAMLObjectBuilder<Audience>) getBuilderFactory().getBuilder(Audience.DEFAULT_ELEMENT_NAME);
155 signatureBuilder = (XMLObjectBuilder<Signature>) getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
159 * Checks that the SAML major version for a request is 2.
161 * @param requestContext current request context containing the SAML message
163 * @throws ProfileException thrown if the major version of the SAML request is not 2
165 protected void checkSamlVersion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
166 SAMLVersion version = requestContext.getInboundSAMLMessage().getVersion();
167 if (version.getMajorVersion() < 2) {
168 requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
169 StatusCode.REQUEST_VERSION_TOO_LOW_URI, null));
170 throw new ProfileException("SAML request version too low");
171 } else if (version.getMajorVersion() > 2) {
172 requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
173 StatusCode.REQUEST_VERSION_TOO_HIGH_URI, null));
174 throw new ProfileException("SAML request version too high");
179 * Builds a response to the attribute query within the request context.
181 * @param requestContext current request context
182 * @param subjectConfirmationMethod confirmation method used for the subject
183 * @param statements the statements to include in the response
185 * @return the built response
187 * @throws ProfileException thrown if there is a problem creating the SAML response
189 protected Response buildResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext,
190 String subjectConfirmationMethod, List<Statement> statements) throws ProfileException {
192 DateTime issueInstant = new DateTime();
194 Subject subject = buildSubject(requestContext, subjectConfirmationMethod, issueInstant);
196 // create the assertion and add the attribute statement
197 Assertion assertion = buildAssertion(requestContext, issueInstant);
198 assertion.setSubject(subject);
199 if (statements != null) {
200 assertion.getStatements().addAll(statements);
203 // create the SAML response and add the assertion
204 Response samlResponse = responseBuilder.buildObject();
205 samlResponse.setIssueInstant(issueInstant);
206 populateStatusResponse(requestContext, samlResponse);
208 samlResponse.getAssertions().add(assertion);
210 // sign the assertion if it should be signed
211 signAssertion(requestContext, assertion);
213 Status status = buildStatus(StatusCode.SUCCESS_URI, null, null);
214 samlResponse.setStatus(status);
220 * Builds a basic assertion with its id, issue instant, SAML version, issuer, subject, and conditions populated.
222 * @param requestContext current request context
223 * @param issueInstant time to use as assertion issue instant
225 * @return the built assertion
227 protected Assertion buildAssertion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
228 Assertion assertion = assertionBuilder.buildObject();
229 assertion.setID(getIdGenerator().generateIdentifier());
230 assertion.setIssueInstant(issueInstant);
231 assertion.setVersion(SAMLVersion.VERSION_20);
232 assertion.setIssuer(buildEntityIssuer(requestContext));
234 Conditions conditions = buildConditions(requestContext, issueInstant);
235 assertion.setConditions(conditions);
241 * Creates an {@link Issuer} populated with information about the relying party.
243 * @param requestContext current request context
245 * @return the built issuer
247 protected Issuer buildEntityIssuer(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) {
248 Issuer issuer = issuerBuilder.buildObject();
249 issuer.setFormat(Issuer.ENTITY);
250 issuer.setValue(requestContext.getLocalEntityId());
256 * Builds a SAML assertion condition set. The following fields are set; not before, not on or after, audience
257 * restrictions, and proxy restrictions.
259 * @param requestContext current request context
260 * @param issueInstant timestamp the assertion was created
262 * @return constructed conditions
264 protected Conditions buildConditions(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
265 AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
267 Conditions conditions = conditionsBuilder.buildObject();
268 conditions.setNotBefore(issueInstant);
269 conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
271 Collection<String> audiences;
273 // add audience restrictions
274 audiences = profileConfig.getAssertionAudiences();
275 if (audiences != null && audiences.size() > 0) {
276 AudienceRestriction audienceRestriction = audienceRestrictionBuilder.buildObject();
277 for (String audienceUri : audiences) {
278 Audience audience = audienceBuilder.buildObject();
279 audience.setAudienceURI(audienceUri);
280 audienceRestriction.getAudiences().add(audience);
282 conditions.getAudienceRestrictions().add(audienceRestriction);
285 // add proxy restrictions
286 audiences = profileConfig.getProxyAudiences();
287 if (audiences != null && audiences.size() > 0) {
288 ProxyRestriction proxyRestriction = proxyRestrictionBuilder.buildObject();
290 for (String audienceUri : audiences) {
291 audience = audienceBuilder.buildObject();
292 audience.setAudienceURI(audienceUri);
293 proxyRestriction.getAudiences().add(audience);
296 proxyRestriction.setProxyCount(profileConfig.getProxyCount());
297 conditions.getConditions().add(proxyRestriction);
304 * Populates the response's id, in response to, issue instant, version, and issuer properties.
306 * @param requestContext current request context
307 * @param response the response to populate
309 protected void populateStatusResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext,
310 StatusResponseType response) {
311 response.setID(getIdGenerator().generateIdentifier());
312 if (requestContext.getInboundSAMLMessage() != null) {
313 response.setInResponseTo(requestContext.getInboundSAMLMessageId());
315 response.setVersion(SAMLVersion.VERSION_20);
316 response.setIssuer(buildEntityIssuer(requestContext));
320 * Resolves the attributes for the principal.
322 * @param requestContext current request context
324 * @throws ProfileException thrown if there is a problem resolved attributes
326 protected void resolveAttributes(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
327 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
328 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
331 log.debug("Resolving attributes for principal {} of SAML request from relying party {}", requestContext
332 .getPrincipalName(), requestContext.getInboundMessageIssuer());
333 Map<String, BaseAttribute> principalAttributes = attributeAuthority.getAttributes(requestContext);
335 requestContext.setAttributes(principalAttributes);
336 } catch (AttributeRequestException e) {
337 log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
338 + " from relying party " + requestContext.getInboundMessageIssuer(), e);
339 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
340 throw new ProfileException("Error resolving attributes for SAML request "
341 + requestContext.getInboundSAMLMessageId() + " from relying party "
342 + requestContext.getInboundMessageIssuer(), e);
347 * Executes a query for attributes and builds a SAML attribute statement from the results.
349 * @param requestContext current request context
351 * @return attribute statement resulting from the query
353 * @throws ProfileException thrown if there is a problem making the query
355 protected AttributeStatement buildAttributeStatement(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
356 throws ProfileException {
357 log.debug("Creating attribute statement in response to SAML request {} from relying party {}", requestContext
358 .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
360 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
361 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
363 if (requestContext.getInboundSAMLMessage() instanceof AttributeQuery) {
364 return attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext
365 .getInboundSAMLMessage(), requestContext.getPrincipalAttributes().values());
367 return attributeAuthority.buildAttributeStatement(null, requestContext.getPrincipalAttributes()
370 } catch (AttributeRequestException e) {
371 log.error("Error encoding attributes for principal " + requestContext.getPrincipalName(), e);
372 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
373 throw new ProfileException("Error encoding attributes for principal " + requestContext.getPrincipalName(),
379 * Resolves the principal name of the subject of the request.
381 * @param requestContext current request context
383 * @throws ProfileException thrown if the principal name can not be resolved
385 protected void resolvePrincipal(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
386 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
387 if (profileConfiguration == null) {
388 log.error("Unable to resolve principal, no SAML 2 profile configuration for relying party "
389 + requestContext.getInboundMessageIssuer());
390 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
391 "Error resolving principal"));
392 throw new ProfileException(
393 "Unable to resolve principal, no SAML 2 profile configuration for relying party "
394 + requestContext.getInboundMessageIssuer());
396 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
397 log.debug("Resolving principal name for subject of SAML request {} from relying party {}", requestContext
398 .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
401 String principal = attributeAuthority.getPrincipal(requestContext);
402 requestContext.setPrincipalName(principal);
403 } catch (AttributeRequestException e) {
404 log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
405 + " from relying party " + requestContext.getInboundMessageIssuer(), e);
406 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.UNKNOWN_PRINCIPAL_URI,
407 "Error resolving principal"));
408 throw new ProfileException("Error resolving attributes for SAML request "
409 + requestContext.getInboundSAMLMessageId() + " from relying party "
410 + requestContext.getInboundMessageIssuer(), e);
415 * Signs the given assertion if either the current profile configuration or the relying party configuration contains
416 * signing credentials.
418 * @param requestContext current request context
419 * @param assertion assertion to sign
421 * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
422 * required, if a signing credential is not configured
424 protected void signAssertion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, Assertion assertion)
425 throws ProfileException {
426 log.debug("Determining if SAML assertion to relying party {} should be signed", requestContext
427 .getInboundMessageIssuer());
429 boolean signAssertion = false;
431 AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
432 if (profileConfig.getSignAssertions()) {
433 signAssertion = true;
434 log.debug("IdP relying party configuration {} indicates to sign assertions: {}", requestContext
435 .getRelyingPartyConfiguration().getRelyingPartyId(), signAssertion);
438 if (!signAssertion && requestContext.getPeerEntityRoleMetadata() instanceof SPSSODescriptor) {
439 SPSSODescriptor ssoDescriptor = (SPSSODescriptor) requestContext.getPeerEntityRoleMetadata();
440 if (ssoDescriptor.getWantAssertionsSigned() != null) {
441 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
442 log.debug("Entity metadata for relying party {} indicates to sign assertions: {}", requestContext
443 .getInboundMessageIssuer(), signAssertion);
447 if (!signAssertion) {
451 log.debug("Determining signing credntial for assertion to relying party {}", requestContext
452 .getInboundMessageIssuer());
453 Credential signatureCredential = profileConfig.getSigningCredential();
454 if (signatureCredential == null) {
455 signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
458 if (signatureCredential == null) {
459 throw new ProfileException("No signing credential is specified for relying party configuration "
460 + requestContext.getRelyingPartyConfiguration().getProviderId()
461 + " or it's SAML2 attribute query profile configuration");
464 log.debug("Signing assertion to relying party {}", requestContext.getInboundMessageIssuer());
465 Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
467 signature.setSigningCredential(signatureCredential);
469 // TODO pull SecurityConfiguration from SAMLMessageContext? needs to be added
470 // TODO how to pull what keyInfoGenName to use?
471 SecurityHelper.prepareSignatureParams(signature, signatureCredential, null, null);
472 } catch (SecurityException e) {
473 throw new ProfileException("Error preparing signature for signing", e);
476 assertion.setSignature(signature);
478 Marshaller assertionMarshaller = Configuration.getMarshallerFactory().getMarshaller(assertion);
480 assertionMarshaller.marshall(assertion);
481 Signer.signObject(signature);
482 } catch (MarshallingException e) {
483 log.error("Unable to marshall assertion for signing", e);
484 throw new ProfileException("Unable to marshall assertion for signing", e);
489 * Build a status message, with an optional second-level failure message.
491 * @param topLevelCode The top-level status code. Should be from saml-core-2.0-os, sec. 3.2.2.2
492 * @param secondLevelCode An optional second-level failure code. Should be from saml-core-2.0-is, sec 3.2.2.2. If
493 * null, no second-level Status element will be set.
494 * @param failureMessage An optional second-level failure message
496 * @return a Status object.
498 protected Status buildStatus(String topLevelCode, String secondLevelCode, String failureMessage) {
499 Status status = statusBuilder.buildObject();
501 StatusCode statusCode = statusCodeBuilder.buildObject();
502 statusCode.setValue(DatatypeHelper.safeTrimOrNullString(topLevelCode));
503 status.setStatusCode(statusCode);
505 if (secondLevelCode != null) {
506 StatusCode secondLevelStatusCode = statusCodeBuilder.buildObject();
507 secondLevelStatusCode.setValue(DatatypeHelper.safeTrimOrNullString(secondLevelCode));
508 statusCode.setStatusCode(secondLevelStatusCode);
511 if (failureMessage != null) {
512 StatusMessage msg = statusMessageBuilder.buildObject();
513 msg.setMessage(failureMessage);
514 status.setStatusMessage(msg);
521 * Builds the SAML subject for the user for the service provider.
523 * @param requestContext current request context
524 * @param confirmationMethod subject confirmation method used for the subject
525 * @param issueInstant instant the subject confirmation data should reflect for issuance
527 * @return SAML subject for the user for the service provider
529 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
530 * name ID attribute or because there are no supported name formats
532 protected Subject buildSubject(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, String confirmationMethod,
533 DateTime issueInstant) throws ProfileException {
534 NameID nameID = buildNameId(requestContext);
535 requestContext.setSubjectNameIdentifier(nameID);
536 // TODO handle encryption
538 SubjectConfirmationData confirmationData = subjectConfirmationDataBuilder.buildObject();
539 HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
540 confirmationData.setAddress(inTransport.getPeerAddress());
541 confirmationData.setInResponseTo(requestContext.getInboundSAMLMessageId());
542 confirmationData.setNotOnOrAfter(issueInstant.plus(requestContext.getProfileConfiguration()
543 .getAssertionLifetime()));
545 Endpoint relyingPartyEndpoint = requestContext.getPeerEntityEndpoint();
546 if (relyingPartyEndpoint != null) {
547 if (relyingPartyEndpoint.getResponseLocation() != null) {
548 confirmationData.setRecipient(relyingPartyEndpoint.getResponseLocation());
550 confirmationData.setRecipient(relyingPartyEndpoint.getLocation());
554 SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
555 subjectConfirmation.setMethod(confirmationMethod);
556 subjectConfirmation.setSubjectConfirmationData(confirmationData);
558 Subject subject = subjectBuilder.buildObject();
559 subject.setNameID(nameID);
560 subject.getSubjectConfirmations().add(subjectConfirmation);
566 * Builds a NameID appropriate for this request. NameIDs are built by inspecting the SAML request and metadata,
567 * picking a name format that was requested by the relying party or is mutually supported by both the relying party
568 * and asserting party as described in their metadata entries. Once a set of supported name formats is determined
569 * the principals attributes are inspected for an attribute supported an attribute encoder whose category is one of
570 * the supported name formats.
572 * @param requestContext current request context
574 * @return the NameID appropriate for this request
576 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
577 * name ID attribute or because there are no supported name formats
579 protected NameID buildNameId(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
580 log.debug("Building assertion NameID for principal/relying party:{}/{}", requestContext.getPrincipalName(),
581 requestContext.getInboundMessageIssuer());
582 Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
583 List<String> supportedNameFormats = getNameFormats(requestContext);
585 log.debug("Supported NameID formats: {}", supportedNameFormats);
587 if (principalAttributes == null || supportedNameFormats == null) {
588 log.error("No attributes for principal " + requestContext.getPrincipalName()
589 + " support constructions of NameID");
590 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
591 "Unable to construct NameID"));
592 throw new ProfileException("No principal attributes support NameID construction");
596 SAML2NameIDAttributeEncoder nameIdEncoder;
597 for (BaseAttribute<?> attribute : principalAttributes.values()) {
598 for (AttributeEncoder encoder : attribute.getEncoders()) {
599 if (encoder instanceof SAML2NameIDAttributeEncoder) {
600 nameIdEncoder = (SAML2NameIDAttributeEncoder) encoder;
601 if (supportedNameFormats.contains(nameIdEncoder.getNameFormat())) {
604 "Using attribute {} suppoting NameID format {} to create the NameID for principal.{}",
605 attribute.getId(), nameIdEncoder.getNameFormat());
606 return nameIdEncoder.encode(attribute);
611 log.error("No principal attribute supported encoding into a supported name ID format.");
612 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
613 throw new ProfileException("No principal attribute supported encoding into a supported name ID format.");
614 } catch (AttributeEncodingException e) {
615 log.error("Unable to encode NameID attribute", e);
616 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
617 throw new ProfileException("Unable to encode NameID attribute", e);
622 * Gets the NameID format to use when creating NameIDs for the relying party.
624 * @param requestContext current request context
626 * @return list of nameID formats that may be used with the relying party
628 * @throws ProfileException thrown if there is a problem determing the NameID format to use
630 protected List<String> getNameFormats(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
631 throws ProfileException {
632 ArrayList<String> nameFormats = new ArrayList<String>();
634 // Determine name formats supported by both SP and IdP
635 RoleDescriptor relyingPartyRole = requestContext.getPeerEntityRoleMetadata();
636 if (relyingPartyRole != null) {
637 List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
638 if (relyingPartySupportedFormats != null && !relyingPartySupportedFormats.isEmpty()) {
639 nameFormats.addAll(relyingPartySupportedFormats);
641 RoleDescriptor assertingPartyRole = requestContext.getLocalEntityRoleMetadata();
642 if (assertingPartyRole != null) {
643 List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
644 if (assertingPartySupportedFormats != null && !assertingPartySupportedFormats.isEmpty()) {
645 nameFormats.retainAll(assertingPartySupportedFormats);
651 if (nameFormats.isEmpty()) {
652 nameFormats.add("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
655 // If authn request and name ID policy format specified, make sure it's in the list of supported formats
656 String nameFormat = null;
657 if (requestContext.getInboundSAMLMessage() instanceof AuthnRequest) {
658 AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
659 if (authnRequest.getNameIDPolicy() != null) {
660 nameFormat = DatatypeHelper.safeTrimOrNullString(authnRequest.getNameIDPolicy().getFormat());
661 if (nameFormat != null) {
662 if (nameFormats.contains(nameFormat)) {
664 nameFormats.add(nameFormat);
666 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
667 StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
668 throw new ProfileException("NameID format required by relying party is not supported");
679 * Gets the list of NameID formats supported for a given role.
681 * @param role the role to get the list of supported NameID formats
683 * @return list of supported NameID formats
685 protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
686 List<NameIDFormat> nameIDFormats = null;
688 if (role instanceof SSODescriptor) {
689 nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
690 } else if (role instanceof AuthnAuthorityDescriptor) {
691 nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
692 } else if (role instanceof PDPDescriptor) {
693 nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
694 } else if (role instanceof AttributeAuthorityDescriptor) {
695 nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
698 ArrayList<String> supportedFormats = new ArrayList<String>();
699 if (nameIDFormats != null) {
700 for (NameIDFormat format : nameIDFormats) {
701 supportedFormats.add(format.getFormat());
705 return supportedFormats;
709 * Constructs an SAML response message carrying a request error.
711 * @param requestContext current request context
713 * @return the constructed error response
715 protected Response buildErrorResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) {
716 Response samlResponse = responseBuilder.buildObject();
717 samlResponse.setIssueInstant(new DateTime());
718 populateStatusResponse(requestContext, samlResponse);
720 samlResponse.setStatus(requestContext.getFailureStatus());