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.apache.log4j.Logger;
25 import org.joda.time.DateTime;
26 import org.opensaml.common.SAMLObjectBuilder;
27 import org.opensaml.common.SAMLVersion;
28 import org.opensaml.common.impl.SAMLObjectContentReference;
29 import org.opensaml.log.Level;
30 import org.opensaml.saml2.core.Assertion;
31 import org.opensaml.saml2.core.AttributeQuery;
32 import org.opensaml.saml2.core.AttributeStatement;
33 import org.opensaml.saml2.core.Audience;
34 import org.opensaml.saml2.core.AudienceRestriction;
35 import org.opensaml.saml2.core.AuthnRequest;
36 import org.opensaml.saml2.core.Conditions;
37 import org.opensaml.saml2.core.Issuer;
38 import org.opensaml.saml2.core.NameID;
39 import org.opensaml.saml2.core.ProxyRestriction;
40 import org.opensaml.saml2.core.Response;
41 import org.opensaml.saml2.core.Statement;
42 import org.opensaml.saml2.core.Status;
43 import org.opensaml.saml2.core.StatusCode;
44 import org.opensaml.saml2.core.StatusMessage;
45 import org.opensaml.saml2.core.StatusResponseType;
46 import org.opensaml.saml2.core.Subject;
47 import org.opensaml.saml2.core.SubjectConfirmation;
48 import org.opensaml.saml2.core.SubjectConfirmationData;
49 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
50 import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor;
51 import org.opensaml.saml2.metadata.Endpoint;
52 import org.opensaml.saml2.metadata.NameIDFormat;
53 import org.opensaml.saml2.metadata.PDPDescriptor;
54 import org.opensaml.saml2.metadata.RoleDescriptor;
55 import org.opensaml.saml2.metadata.SPSSODescriptor;
56 import org.opensaml.saml2.metadata.SSODescriptor;
57 import org.opensaml.ws.transport.http.HTTPInTransport;
58 import org.opensaml.xml.XMLObjectBuilder;
59 import org.opensaml.xml.security.credential.Credential;
60 import org.opensaml.xml.signature.Signature;
61 import org.opensaml.xml.signature.Signer;
62 import org.opensaml.xml.util.DatatypeHelper;
64 import edu.internet2.middleware.shibboleth.common.attribute.AttributeRequestException;
65 import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
66 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncoder;
67 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncodingException;
68 import edu.internet2.middleware.shibboleth.common.attribute.encoding.SAML2NameIDAttributeEncoder;
69 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML2AttributeAuthority;
70 import edu.internet2.middleware.shibboleth.common.log.AuditLogEntry;
71 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
72 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AbstractSAML2ProfileConfiguration;
73 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
75 /** Common implementation details for profile handlers. */
76 public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHandler {
78 /** SAML Version for this profile handler. */
79 public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_20;
82 private Logger log = Logger.getLogger(AbstractSAML2ProfileHandler.class);
84 /** For building response. */
85 private SAMLObjectBuilder<Response> responseBuilder;
87 /** For building status. */
88 private SAMLObjectBuilder<Status> statusBuilder;
90 /** For building statuscode. */
91 private SAMLObjectBuilder<StatusCode> statusCodeBuilder;
93 /** For building StatusMessages. */
94 private SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
96 /** For building assertion. */
97 private SAMLObjectBuilder<Assertion> assertionBuilder;
99 /** For building issuer. */
100 private SAMLObjectBuilder<Issuer> issuerBuilder;
102 /** For building subject. */
103 private SAMLObjectBuilder<Subject> subjectBuilder;
105 /** For building subject confirmation. */
106 private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
108 /** For building subject confirmation data. */
109 private SAMLObjectBuilder<SubjectConfirmationData> subjectConfirmationDataBuilder;
111 /** For building conditions. */
112 private SAMLObjectBuilder<Conditions> conditionsBuilder;
114 /** For building audience restriction. */
115 private SAMLObjectBuilder<AudienceRestriction> audienceRestrictionBuilder;
117 /** For building proxy retrictions. */
118 private SAMLObjectBuilder<ProxyRestriction> proxyRestrictionBuilder;
120 /** For building audience. */
121 private SAMLObjectBuilder<Audience> audienceBuilder;
123 /** For building signature. */
124 private XMLObjectBuilder<Signature> signatureBuilder;
127 @SuppressWarnings("unchecked")
128 protected AbstractSAML2ProfileHandler() {
131 responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
132 statusBuilder = (SAMLObjectBuilder<Status>) getBuilderFactory().getBuilder(Status.DEFAULT_ELEMENT_NAME);
133 statusCodeBuilder = (SAMLObjectBuilder<StatusCode>) getBuilderFactory().getBuilder(
134 StatusCode.DEFAULT_ELEMENT_NAME);
135 statusMessageBuilder = (SAMLObjectBuilder<StatusMessage>) getBuilderFactory().getBuilder(
136 StatusMessage.DEFAULT_ELEMENT_NAME);
137 issuerBuilder = (SAMLObjectBuilder<Issuer>) getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
138 assertionBuilder = (SAMLObjectBuilder<Assertion>) getBuilderFactory()
139 .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
140 subjectBuilder = (SAMLObjectBuilder<Subject>) getBuilderFactory().getBuilder(Subject.DEFAULT_ELEMENT_NAME);
141 subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) getBuilderFactory().getBuilder(
142 SubjectConfirmation.DEFAULT_ELEMENT_NAME);
143 subjectConfirmationDataBuilder = (SAMLObjectBuilder<SubjectConfirmationData>) getBuilderFactory().getBuilder(
144 SubjectConfirmationData.DEFAULT_ELEMENT_NAME);
145 conditionsBuilder = (SAMLObjectBuilder<Conditions>) getBuilderFactory().getBuilder(
146 Conditions.DEFAULT_ELEMENT_NAME);
147 audienceRestrictionBuilder = (SAMLObjectBuilder<AudienceRestriction>) getBuilderFactory().getBuilder(
148 AudienceRestriction.DEFAULT_ELEMENT_NAME);
149 proxyRestrictionBuilder = (SAMLObjectBuilder<ProxyRestriction>) getBuilderFactory().getBuilder(
150 ProxyRestriction.DEFAULT_ELEMENT_NAME);
151 audienceBuilder = (SAMLObjectBuilder<Audience>) getBuilderFactory().getBuilder(Audience.DEFAULT_ELEMENT_NAME);
152 signatureBuilder = (XMLObjectBuilder<Signature>) getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
156 * Checks that the SAML major version for a request is 2.
158 * @param requestContext current request context containing the SAML message
160 * @throws ProfileException thrown if the major version of the SAML request is not 2
162 protected void checkSamlVersion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
163 SAMLVersion version = requestContext.getInboundSAMLMessage().getVersion();
164 if (version.getMajorVersion() < 2) {
165 requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
166 StatusCode.REQUEST_VERSION_TOO_LOW_URI, null));
167 throw new ProfileException("SAML request version too low");
168 } else if (version.getMajorVersion() > 2) {
169 requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
170 StatusCode.REQUEST_VERSION_TOO_HIGH_URI, null));
171 throw new ProfileException("SAML request version too high");
176 * Builds a response to the attribute query within the request context.
178 * @param requestContext current request context
179 * @param subjectConfirmationMethod confirmation method used for the subject
180 * @param statements the statements to include in the response
182 * @return the built response
184 * @throws ProfileException thrown if there is a problem creating the SAML response
186 protected Response buildResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext,
187 String subjectConfirmationMethod, List<Statement> statements) throws ProfileException {
189 DateTime issueInstant = new DateTime();
191 Subject subject = buildSubject(requestContext, subjectConfirmationMethod, issueInstant);
193 // create the assertion and add the attribute statement
194 Assertion assertion = buildAssertion(requestContext, issueInstant);
195 assertion.setSubject(subject);
196 if (statements != null) {
197 assertion.getStatements().addAll(statements);
200 // create the SAML response and add the assertion
201 Response samlResponse = responseBuilder.buildObject();
202 samlResponse.setIssueInstant(issueInstant);
203 populateStatusResponse(requestContext, samlResponse);
205 samlResponse.getAssertions().add(assertion);
207 // sign the assertion if it should be signed
208 signAssertion(requestContext, assertion);
210 Status status = buildStatus(StatusCode.SUCCESS_URI, null, null);
211 samlResponse.setStatus(status);
217 * Builds a basic assertion with its id, issue instant, SAML version, issuer, subject, and conditions populated.
219 * @param requestContext current request context
220 * @param issueInstant time to use as assertion issue instant
222 * @return the built assertion
224 protected Assertion buildAssertion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
225 Assertion assertion = assertionBuilder.buildObject();
226 assertion.setID(getIdGenerator().generateIdentifier());
227 assertion.setIssueInstant(issueInstant);
228 assertion.setVersion(SAMLVersion.VERSION_20);
229 assertion.setIssuer(buildEntityIssuer(requestContext));
231 Conditions conditions = buildConditions(requestContext, issueInstant);
232 assertion.setConditions(conditions);
238 * Creates an {@link Issuer} populated with information about the relying party.
240 * @param requestContext current request context
242 * @return the built issuer
244 protected Issuer buildEntityIssuer(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) {
245 Issuer issuer = issuerBuilder.buildObject();
246 issuer.setFormat(Issuer.ENTITY);
247 issuer.setValue(requestContext.getAssertingPartyEntityId());
253 * Builds a SAML assertion condition set. The following fields are set; not before, not on or after, audience
254 * restrictions, and proxy restrictions.
256 * @param requestContext current request context
257 * @param issueInstant timestamp the assertion was created
259 * @return constructed conditions
261 protected Conditions buildConditions(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
262 AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
264 Conditions conditions = conditionsBuilder.buildObject();
265 conditions.setNotBefore(issueInstant);
266 conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
268 Collection<String> audiences;
270 // add audience restrictions
271 audiences = profileConfig.getAssertionAudiences();
272 if (audiences != null && audiences.size() > 0) {
273 AudienceRestriction audienceRestriction = audienceRestrictionBuilder.buildObject();
274 for (String audienceUri : audiences) {
275 Audience audience = audienceBuilder.buildObject();
276 audience.setAudienceURI(audienceUri);
277 audienceRestriction.getAudiences().add(audience);
279 conditions.getAudienceRestrictions().add(audienceRestriction);
282 // add proxy restrictions
283 audiences = profileConfig.getProxyAudiences();
284 if (audiences != null && audiences.size() > 0) {
285 ProxyRestriction proxyRestriction = proxyRestrictionBuilder.buildObject();
287 for (String audienceUri : audiences) {
288 audience = audienceBuilder.buildObject();
289 audience.setAudienceURI(audienceUri);
290 proxyRestriction.getAudiences().add(audience);
293 proxyRestriction.setProxyCount(profileConfig.getProxyCount());
294 conditions.getConditions().add(proxyRestriction);
301 * Populates the response's id, in response to, issue instant, version, and issuer properties.
303 * @param requestContext current request context
304 * @param response the response to populate
306 protected void populateStatusResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext,
307 StatusResponseType response) {
308 response.setID(getIdGenerator().generateIdentifier());
309 if (requestContext.getInboundSAMLMessage() != null) {
310 response.setInResponseTo(requestContext.getInboundSAMLMessageId());
312 response.setVersion(SAMLVersion.VERSION_20);
313 response.setIssuer(buildEntityIssuer(requestContext));
317 * Resolves the attributes for the principal.
319 * @param requestContext current request context
321 * @throws ProfileException thrown if there is a problem resolved attributes
323 protected void resolveAttributes(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
324 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
325 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
328 if (log.isDebugEnabled()) {
329 log.debug("Resolving attributes for principal " + requestContext.getPrincipalName()
330 + " of SAML request " + requestContext.getInboundSAMLMessageId() + " from relying party "
331 + requestContext.getRelyingPartyEntityId());
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.getRelyingPartyEntityId(), 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.getRelyingPartyEntityId(), 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 if (log.isDebugEnabled()) {
358 log.debug("Creating attribute statement in response to SAML request "
359 + requestContext.getInboundSAMLMessageId() + " from relying party "
360 + requestContext.getRelyingPartyEntityId());
362 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
363 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
365 if (requestContext.getInboundSAMLMessage() instanceof AttributeQuery) {
366 return attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext
367 .getInboundSAMLMessage(), requestContext.getPrincipalAttributes().values());
369 return attributeAuthority.buildAttributeStatement(null, requestContext.getPrincipalAttributes()
372 } catch (AttributeRequestException e) {
373 log.error("Error encoding attributes for principal " + requestContext.getPrincipalName(), e);
374 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
375 throw new ProfileException("Error encoding attributes for principal " + requestContext.getPrincipalName(),
381 * Resolves the principal name of the subject of the request.
383 * @param requestContext current request context
385 * @throws ProfileException thrown if the principal name can not be resolved
387 protected void resolvePrincipal(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
388 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
389 if (profileConfiguration == null) {
390 log.error("Unable to resolve principal, no SAML 2 profile configuration for relying party "
391 + requestContext.getRelyingPartyEntityId());
392 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
393 "Error resolving principal"));
394 throw new ProfileException(
395 "Unable to resolve principal, no SAML 2 profile configuration for relying party "
396 + requestContext.getRelyingPartyEntityId());
398 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
400 if (log.isDebugEnabled()) {
401 log.debug("Resolving principal name for subject of SAML request "
402 + requestContext.getInboundSAMLMessageId() + " from relying party "
403 + requestContext.getRelyingPartyEntityId());
407 String principal = attributeAuthority.getPrincipal(requestContext);
408 requestContext.setPrincipalName(principal);
409 } catch (AttributeRequestException e) {
410 log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
411 + " from relying party " + requestContext.getRelyingPartyEntityId(), e);
412 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.UNKNOWN_PRINCIPAL_URI,
413 "Error resolving principal"));
414 throw new ProfileException("Error resolving attributes for SAML request "
415 + requestContext.getInboundSAMLMessageId() + " from relying party "
416 + requestContext.getRelyingPartyEntityId(), e);
421 * Signs the given assertion if either the current profile configuration or the relying party configuration contains
422 * signing credentials.
424 * @param requestContext current request context
425 * @param assertion assertion to sign
427 * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
428 * required, if a signing credential is not configured
430 protected void signAssertion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, Assertion assertion)
431 throws ProfileException {
432 if (log.isDebugEnabled()) {
433 log.debug("Determining if SAML assertion to relying party " + requestContext.getRelyingPartyEntityId()
434 + " should be signed");
437 boolean signAssertion = false;
439 AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
441 if (requestContext.getPeerEntityRoleMetadata() instanceof SPSSODescriptor) {
442 SPSSODescriptor ssoDescriptor = (SPSSODescriptor) requestContext.getPeerEntityRoleMetadata();
443 if (ssoDescriptor.getWantAssertionsSigned() != null) {
444 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
445 if (log.isDebugEnabled()) {
446 log.debug("Entity metadata for relying party " + requestContext.getRelyingPartyEntityId()
447 + " indicates to sign assertions: " + signAssertion);
450 } else if (profileConfig.getSignAssertions()) {
451 signAssertion = true;
452 log.debug("IdP relying party configuration "
453 + requestContext.getRelyingPartyConfiguration().getRelyingPartyId()
454 + " indicates to sign assertions: " + signAssertion);
457 if (!signAssertion) {
461 if (log.isDebugEnabled()) {
462 log.debug("Determining signing credntial for assertion to relying party "
463 + requestContext.getRelyingPartyEntityId());
465 Credential signatureCredential = profileConfig.getSigningCredential();
466 if (signatureCredential == null) {
467 signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
470 if (signatureCredential == null) {
471 throw new ProfileException("No signing credential is specified for relying party configuration "
472 + requestContext.getRelyingPartyConfiguration().getProviderId()
473 + " or it's SAML2 attribute query profile configuration");
476 if (log.isDebugEnabled()) {
477 log.debug("Signing assertion to relying party " + requestContext.getRelyingPartyEntityId());
479 SAMLObjectContentReference contentRef = new SAMLObjectContentReference(assertion);
480 Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
481 signature.getContentReferences().add(contentRef);
482 assertion.setSignature(signature);
484 Signer.signObject(signature);
488 * Build a status message, with an optional second-level failure message.
490 * @param topLevelCode The top-level status code. Should be from saml-core-2.0-os, sec. 3.2.2.2
491 * @param secondLevelCode An optional second-level failure code. Should be from saml-core-2.0-is, sec 3.2.2.2. If
492 * null, no second-level Status element will be set.
493 * @param failureMessage An optional second-level failure message
495 * @return a Status object.
497 protected Status buildStatus(String topLevelCode, String secondLevelCode, String failureMessage) {
498 Status status = statusBuilder.buildObject();
500 StatusCode statusCode = statusCodeBuilder.buildObject();
501 statusCode.setValue(DatatypeHelper.safeTrimOrNullString(topLevelCode));
502 status.setStatusCode(statusCode);
504 if (secondLevelCode != null) {
505 StatusCode secondLevelStatusCode = statusCodeBuilder.buildObject();
506 secondLevelStatusCode.setValue(DatatypeHelper.safeTrimOrNullString(secondLevelCode));
507 statusCode.setStatusCode(secondLevelStatusCode);
510 if (failureMessage != null) {
511 StatusMessage msg = statusMessageBuilder.buildObject();
512 msg.setMessage(failureMessage);
513 status.setStatusMessage(msg);
520 * Builds the SAML subject for the user for the service provider.
522 * @param requestContext current request context
523 * @param confirmationMethod subject confirmation method used for the subject
524 * @param issueInstant instant the subject confirmation data should reflect for issuance
526 * @return SAML subject for the user for the service provider
528 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
529 * name ID attribute or because there are no supported name formats
531 protected Subject buildSubject(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, String confirmationMethod,
532 DateTime issueInstant) throws ProfileException {
533 NameID nameID = buildNameId(requestContext);
534 requestContext.setSubjectNameIdentifier(nameID);
535 // TODO handle encryption
537 SubjectConfirmationData confirmationData = subjectConfirmationDataBuilder.buildObject();
538 HTTPInTransport inTransport = (HTTPInTransport) requestContext.getMessageInTransport();
539 confirmationData.setAddress(inTransport.getPeerAddress());
540 confirmationData.setInResponseTo(requestContext.getInboundSAMLMessageId());
541 confirmationData.setNotOnOrAfter(issueInstant.plus(requestContext.getProfileConfiguration()
542 .getAssertionLifetime()));
544 Endpoint relyingPartyEndpoint = requestContext.getPeerEntityEndpoint();
545 if (relyingPartyEndpoint != null) {
546 if (relyingPartyEndpoint.getResponseLocation() != null) {
547 confirmationData.setRecipient(relyingPartyEndpoint.getResponseLocation());
549 confirmationData.setRecipient(relyingPartyEndpoint.getLocation());
553 SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
554 subjectConfirmation.setMethod(confirmationMethod);
555 subjectConfirmation.setSubjectConfirmationData(confirmationData);
557 Subject subject = subjectBuilder.buildObject();
558 subject.setNameID(nameID);
559 subject.getSubjectConfirmations().add(subjectConfirmation);
565 * Builds a NameID appropriate for this request. NameIDs are built by inspecting the SAML request and metadata,
566 * picking a name format that was requested by the relying party or is mutually supported by both the relying party
567 * and asserting party as described in their metadata entries. Once a set of supported name formats is determined
568 * the principals attributes are inspected for an attribute supported an attribute encoder whose category is one of
569 * the supported name formats.
571 * @param requestContext current request context
573 * @return the NameID appropriate for this request
575 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
576 * name ID attribute or because there are no supported name formats
578 protected NameID buildNameId(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
579 if (log.isDebugEnabled()) {
580 log.debug("Building assertion NameID for principal/relying party:" + requestContext.getPrincipalName()
581 + "/" + requestContext.getRelyingPartyEntityId());
583 Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
584 List<String> supportedNameFormats = getNameFormats(requestContext);
586 if (log.isDebugEnabled()) {
587 log.debug("Supported NameID formats: " + supportedNameFormats);
590 if (principalAttributes == null || supportedNameFormats == null) {
591 log.error("No attributes for principal " + requestContext.getPrincipalName()
592 + " support constructions of NameID");
593 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
594 "Unable to construct NameID"));
595 throw new ProfileException("No principal attributes support NameID construction");
599 SAML2NameIDAttributeEncoder nameIdEncoder;
600 for (BaseAttribute<?> attribute : principalAttributes.values()) {
601 for (AttributeEncoder encoder : attribute.getEncoders()) {
602 if (encoder instanceof SAML2NameIDAttributeEncoder) {
603 nameIdEncoder = (SAML2NameIDAttributeEncoder) encoder;
604 if (supportedNameFormats.contains(nameIdEncoder.getNameFormat())) {
605 if (log.isDebugEnabled()) {
606 log.debug("Using attribute " + attribute.getId() + " suppoting NameID format "
607 + nameIdEncoder.getNameFormat() + " to create the NameID for principal "
608 + requestContext.getPrincipalName());
610 return nameIdEncoder.encode(attribute);
615 log.error("No principal attribute supported encoding into a supported name ID format.");
616 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
617 throw new ProfileException("No principal attribute supported encoding into a supported name ID format.");
618 } catch (AttributeEncodingException e) {
619 log.error("Unable to encode NameID attribute", e);
620 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
621 throw new ProfileException("Unable to encode NameID attribute", e);
626 * Gets the NameID format to use when creating NameIDs for the relying party.
628 * @param requestContext current request context
630 * @return list of nameID formats that may be used with the relying party
632 * @throws ProfileException thrown if there is a problem determing the NameID format to use
634 protected List<String> getNameFormats(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
635 throws ProfileException {
636 ArrayList<String> nameFormats = new ArrayList<String>();
638 List<String> assertingPartySupportedFormats = getEntitySupportedFormats(requestContext
639 .getLocalEntityRoleMetadata());
641 String nameFormat = null;
642 if (requestContext.getInboundSAMLMessage() instanceof AuthnRequest) {
643 AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
644 if (authnRequest.getNameIDPolicy() != null && !DatatypeHelper.isEmpty(nameFormat)) {
645 nameFormat = authnRequest.getNameIDPolicy().getFormat();
646 if (assertingPartySupportedFormats.contains(nameFormat)) {
647 nameFormats.add(nameFormat);
649 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
650 StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
651 throw new ProfileException("NameID format required by relying party is not supported");
656 if (nameFormats.isEmpty()) {
657 List<String> relyingPartySupportedFormats = getEntitySupportedFormats(requestContext
658 .getPeerEntityRoleMetadata());
660 assertingPartySupportedFormats.retainAll(relyingPartySupportedFormats);
661 nameFormats.addAll(assertingPartySupportedFormats);
663 if (nameFormats.isEmpty()) {
664 nameFormats.add("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
671 * Gets the list of NameID formats supported for a given role.
673 * @param role the role to get the list of supported NameID formats
675 * @return list of supported NameID formats
677 protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
678 List<NameIDFormat> nameIDFormats = null;
680 if (role instanceof SSODescriptor) {
681 nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
682 } else if (role instanceof AuthnAuthorityDescriptor) {
683 nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
684 } else if (role instanceof PDPDescriptor) {
685 nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
686 } else if (role instanceof AttributeAuthorityDescriptor) {
687 nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
690 ArrayList<String> supportedFormats = new ArrayList<String>();
691 if (nameIDFormats != null) {
692 for (NameIDFormat format : nameIDFormats) {
693 supportedFormats.add(format.getFormat());
697 return supportedFormats;
701 * Constructs an SAML response message carrying a request error.
703 * @param requestContext current request context
705 * @return the constructed error response
707 protected Response buildErrorResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) {
708 Response samlResponse = responseBuilder.buildObject();
709 samlResponse.setIssueInstant(new DateTime());
710 populateStatusResponse(requestContext, samlResponse);
712 samlResponse.setStatus(requestContext.getFailureStatus());
718 * Writes an aduit log entry indicating the successful response to the attribute request.
720 * @param context current request context
722 protected void writeAuditLogEntry(BaseSAML2ProfileRequestContext<?, ?, ?> context) {
723 AuditLogEntry auditLogEntry = new AuditLogEntry();
724 auditLogEntry.setMessageProfile(getProfileId());
725 auditLogEntry.setPrincipalAuthenticationMethod(context.getPrincipalAuthenticationMethod());
726 auditLogEntry.setPrincipalName(context.getPrincipalName());
727 auditLogEntry.setAssertingPartyId(context.getAssertingPartyEntityId());
728 auditLogEntry.setRelyingPartyId(context.getRelyingPartyEntityId());
729 auditLogEntry.setRequestBinding(getMessageDecoder().getBindingURI());
730 auditLogEntry.setRequestId(context.getInboundSAMLMessageId());
731 auditLogEntry.setResponseBinding(getMessageEncoder().getBindingURI());
732 auditLogEntry.setResponseId(context.getOutboundSAMLMessageId());
733 if (context.getReleasedAttributes() != null) {
734 auditLogEntry.getReleasedAttributes().addAll(context.getReleasedAttributes());
736 getAduitLog().log(Level.CRITICAL, auditLogEntry);