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;
26 import org.apache.log4j.Logger;
27 import org.joda.time.DateTime;
28 import org.opensaml.common.SAMLObject;
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.Assertion;
34 import org.opensaml.saml2.core.AttributeQuery;
35 import org.opensaml.saml2.core.AttributeStatement;
36 import org.opensaml.saml2.core.Audience;
37 import org.opensaml.saml2.core.AudienceRestriction;
38 import org.opensaml.saml2.core.AuthnRequest;
39 import org.opensaml.saml2.core.Conditions;
40 import org.opensaml.saml2.core.Issuer;
41 import org.opensaml.saml2.core.NameID;
42 import org.opensaml.saml2.core.ProxyRestriction;
43 import org.opensaml.saml2.core.RequestAbstractType;
44 import org.opensaml.saml2.core.Response;
45 import org.opensaml.saml2.core.Statement;
46 import org.opensaml.saml2.core.Status;
47 import org.opensaml.saml2.core.StatusCode;
48 import org.opensaml.saml2.core.StatusMessage;
49 import org.opensaml.saml2.core.StatusResponseType;
50 import org.opensaml.saml2.core.Subject;
51 import org.opensaml.saml2.core.SubjectConfirmation;
52 import org.opensaml.saml2.core.SubjectConfirmationData;
53 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
54 import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor;
55 import org.opensaml.saml2.metadata.Endpoint;
56 import org.opensaml.saml2.metadata.NameIDFormat;
57 import org.opensaml.saml2.metadata.PDPDescriptor;
58 import org.opensaml.saml2.metadata.RoleDescriptor;
59 import org.opensaml.saml2.metadata.SPSSODescriptor;
60 import org.opensaml.saml2.metadata.SSODescriptor;
61 import org.opensaml.ws.transport.http.HTTPInTransport;
62 import org.opensaml.xml.XMLObjectBuilder;
63 import org.opensaml.xml.security.credential.Credential;
64 import org.opensaml.xml.signature.Signature;
65 import org.opensaml.xml.signature.Signer;
66 import org.opensaml.xml.util.DatatypeHelper;
68 import edu.internet2.middleware.shibboleth.common.attribute.AttributeRequestException;
69 import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
70 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncoder;
71 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncodingException;
72 import edu.internet2.middleware.shibboleth.common.attribute.encoding.SAML2NameIDAttributeEncoder;
73 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML2AttributeAuthority;
74 import edu.internet2.middleware.shibboleth.common.attribute.provider.ShibbolethSAMLAttributeRequestContext;
75 import edu.internet2.middleware.shibboleth.common.log.AuditLogEntry;
76 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
77 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
78 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AbstractSAML2ProfileConfiguration;
79 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
80 import edu.internet2.middleware.shibboleth.idp.session.ServiceInformation;
81 import edu.internet2.middleware.shibboleth.idp.session.Session;
83 /** Common implementation details for profile handlers. */
84 public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHandler {
86 /** SAML Version for this profile handler. */
87 public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_20;
90 private Logger log = Logger.getLogger(AbstractSAML2ProfileHandler.class);
92 /** For building response. */
93 private SAMLObjectBuilder<Response> responseBuilder;
95 /** For building status. */
96 private SAMLObjectBuilder<Status> statusBuilder;
98 /** For building statuscode. */
99 private SAMLObjectBuilder<StatusCode> statusCodeBuilder;
101 /** For building StatusMessages. */
102 private SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
104 /** For building assertion. */
105 private SAMLObjectBuilder<Assertion> assertionBuilder;
107 /** For building issuer. */
108 private SAMLObjectBuilder<Issuer> issuerBuilder;
110 /** For building subject. */
111 private SAMLObjectBuilder<Subject> subjectBuilder;
113 /** For building subject confirmation. */
114 private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
116 /** For building subject confirmation data. */
117 private SAMLObjectBuilder<SubjectConfirmationData> subjectConfirmationDataBuilder;
119 /** For building conditions. */
120 private SAMLObjectBuilder<Conditions> conditionsBuilder;
122 /** For building audience restriction. */
123 private SAMLObjectBuilder<AudienceRestriction> audienceRestrictionBuilder;
125 /** For building proxy retrictions. */
126 private SAMLObjectBuilder<ProxyRestriction> proxyRestrictionBuilder;
128 /** For building audience. */
129 private SAMLObjectBuilder<Audience> audienceBuilder;
131 /** For building signature. */
132 private XMLObjectBuilder<Signature> signatureBuilder;
135 @SuppressWarnings("unchecked")
136 protected AbstractSAML2ProfileHandler() {
139 responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
140 statusBuilder = (SAMLObjectBuilder<Status>) getBuilderFactory().getBuilder(Status.DEFAULT_ELEMENT_NAME);
141 statusCodeBuilder = (SAMLObjectBuilder<StatusCode>) getBuilderFactory().getBuilder(
142 StatusCode.DEFAULT_ELEMENT_NAME);
143 statusMessageBuilder = (SAMLObjectBuilder<StatusMessage>) getBuilderFactory().getBuilder(
144 StatusMessage.DEFAULT_ELEMENT_NAME);
145 issuerBuilder = (SAMLObjectBuilder<Issuer>) getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
146 assertionBuilder = (SAMLObjectBuilder<Assertion>) getBuilderFactory()
147 .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
148 subjectBuilder = (SAMLObjectBuilder<Subject>) getBuilderFactory().getBuilder(Subject.DEFAULT_ELEMENT_NAME);
149 subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) getBuilderFactory().getBuilder(
150 SubjectConfirmation.DEFAULT_ELEMENT_NAME);
151 subjectConfirmationDataBuilder = (SAMLObjectBuilder<SubjectConfirmationData>) getBuilderFactory().getBuilder(
152 SubjectConfirmationData.DEFAULT_ELEMENT_NAME);
153 conditionsBuilder = (SAMLObjectBuilder<Conditions>) getBuilderFactory().getBuilder(
154 Conditions.DEFAULT_ELEMENT_NAME);
155 audienceRestrictionBuilder = (SAMLObjectBuilder<AudienceRestriction>) getBuilderFactory().getBuilder(
156 AudienceRestriction.DEFAULT_ELEMENT_NAME);
157 proxyRestrictionBuilder = (SAMLObjectBuilder<ProxyRestriction>) getBuilderFactory().getBuilder(
158 ProxyRestriction.DEFAULT_ELEMENT_NAME);
159 audienceBuilder = (SAMLObjectBuilder<Audience>) getBuilderFactory().getBuilder(Audience.DEFAULT_ELEMENT_NAME);
160 signatureBuilder = (XMLObjectBuilder<Signature>) getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
164 * Checks that the SAML major version for a request is 2.
166 * @param requestContext current request context containing the SAML message
168 * @throws ProfileException thrown if the major version of the SAML request is not 2
170 protected void checkSamlVersion(BaseSAML2ProfileRequestContext<?,?,?> requestContext) throws ProfileException {
171 SAMLVersion version = requestContext.getInboundSAMLMessage().getVersion();
172 if (version.getMajorVersion() < 2) {
173 requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
174 StatusCode.REQUEST_VERSION_TOO_LOW_URI, null));
175 throw new ProfileException("SAML request version too low");
176 } else if (version.getMajorVersion() > 2) {
177 requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
178 StatusCode.REQUEST_VERSION_TOO_HIGH_URI, null));
179 throw new ProfileException("SAML request version too high");
184 * Builds a response to the attribute query within the request context.
186 * @param requestContext current request context
187 * @param subjectConfirmationMethod confirmation method used for the subject
188 * @param statements the statements to include in the response
190 * @return the built response
192 * @throws ProfileException thrown if there is a problem creating the SAML response
194 protected Response buildResponse(BaseSAML2ProfileRequestContext<?,?,?> requestContext, String subjectConfirmationMethod,
195 List<Statement> statements) throws ProfileException {
197 DateTime issueInstant = new DateTime();
199 Subject subject = buildSubject(requestContext, subjectConfirmationMethod, issueInstant);
201 // create the assertion and add the attribute statement
202 Assertion assertion = buildAssertion(requestContext, issueInstant);
203 assertion.setSubject(subject);
204 if (statements != null) {
205 assertion.getStatements().addAll(statements);
208 // create the SAML response and add the assertion
209 Response samlResponse = responseBuilder.buildObject();
210 samlResponse.setIssueInstant(issueInstant);
211 populateStatusResponse(requestContext, samlResponse);
213 samlResponse.getAssertions().add(assertion);
215 // sign the assertion if it should be signed
216 signAssertion(requestContext, assertion);
218 Status status = buildStatus(StatusCode.SUCCESS_URI, null, null);
219 samlResponse.setStatus(status);
225 * Builds a basic assertion with its id, issue instant, SAML version, issuer, subject, and conditions populated.
227 * @param requestContext current request context
228 * @param issueInstant time to use as assertion issue instant
230 * @return the built assertion
232 protected Assertion buildAssertion(BaseSAML2ProfileRequestContext<?,?,?> requestContext, DateTime issueInstant) {
233 Assertion assertion = assertionBuilder.buildObject();
234 assertion.setID(getIdGenerator().generateIdentifier());
235 assertion.setIssueInstant(issueInstant);
236 assertion.setVersion(SAMLVersion.VERSION_20);
237 assertion.setIssuer(buildEntityIssuer(requestContext));
239 Conditions conditions = buildConditions(requestContext, issueInstant);
240 assertion.setConditions(conditions);
246 * Creates an {@link Issuer} populated with information about the relying party.
248 * @param requestContext current request context
250 * @return the built issuer
252 protected Issuer buildEntityIssuer(BaseSAML2ProfileRequestContext<?,?,?> requestContext) {
253 Issuer issuer = issuerBuilder.buildObject();
254 issuer.setFormat(Issuer.ENTITY);
255 issuer.setValue(requestContext.getAssertingPartyEntityId());
261 * Builds a SAML assertion condition set. The following fields are set; not before, not on or after, audience
262 * restrictions, and proxy restrictions.
264 * @param requestContext current request context
265 * @param issueInstant timestamp the assertion was created
267 * @return constructed conditions
269 protected Conditions buildConditions(BaseSAML2ProfileRequestContext<?,?,?> requestContext, DateTime issueInstant) {
270 AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
272 Conditions conditions = conditionsBuilder.buildObject();
273 conditions.setNotBefore(issueInstant);
274 conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
276 Collection<String> audiences;
278 // add audience restrictions
279 audiences = profileConfig.getAssertionAudiences();
280 if (audiences != null && audiences.size() > 0) {
281 AudienceRestriction audienceRestriction = audienceRestrictionBuilder.buildObject();
282 for (String audienceUri : audiences) {
283 Audience audience = audienceBuilder.buildObject();
284 audience.setAudienceURI(audienceUri);
285 audienceRestriction.getAudiences().add(audience);
287 conditions.getAudienceRestrictions().add(audienceRestriction);
290 // add proxy restrictions
291 audiences = profileConfig.getProxyAudiences();
292 if (audiences != null && audiences.size() > 0) {
293 ProxyRestriction proxyRestriction = proxyRestrictionBuilder.buildObject();
295 for (String audienceUri : audiences) {
296 audience = audienceBuilder.buildObject();
297 audience.setAudienceURI(audienceUri);
298 proxyRestriction.getAudiences().add(audience);
301 proxyRestriction.setProxyCount(profileConfig.getProxyCount());
302 conditions.getConditions().add(proxyRestriction);
309 * Populates the response's id, in response to, issue instant, version, and issuer properties.
311 * @param requestContext current request context
312 * @param response the response to populate
314 protected void populateStatusResponse(BaseSAML2ProfileRequestContext<?,?,?> requestContext, StatusResponseType response) {
315 response.setID(getIdGenerator().generateIdentifier());
316 if (requestContext.getInboundSAMLMessage() != null) {
317 response.setInResponseTo(requestContext.getInboundSAMLMessageId());
319 response.setVersion(SAMLVersion.VERSION_20);
320 response.setIssuer(buildEntityIssuer(requestContext));
324 * Resolves the attributes for the principal.
326 * @param requestContext current request context
328 * @throws ProfileException thrown if there is a problem resolved attributes
330 protected void resolveAttributes(BaseSAML2ProfileRequestContext<?,?,?> requestContext) throws ProfileException{
331 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
332 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
335 if (log.isDebugEnabled()) {
336 log.debug("Resolving attributes for principal " + requestContext.getPrincipalName()
337 + " of SAML request " + requestContext.getInboundSAMLMessageId() + " from relying party "
338 + requestContext.getRelyingPartyEntityId());
340 Map<String, BaseAttribute> principalAttributes = attributeAuthority
341 .getAttributes(buildAttributeRequestContext(requestContext));
343 requestContext.setPrincipalAttributes(principalAttributes);
344 } catch (AttributeRequestException e) {
345 log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
346 + " from relying party " + requestContext.getRelyingPartyEntityId(), e);
347 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
348 throw new ProfileException("Error resolving attributes for SAML request "
349 + requestContext.getInboundSAMLMessageId() + " from relying party "
350 + requestContext.getRelyingPartyEntityId(), e);
355 * Executes a query for attributes and builds a SAML attribute statement from the results.
357 * @param requestContext current request context
359 * @return attribute statement resulting from the query
361 * @throws ProfileException thrown if there is a problem making the query
363 protected AttributeStatement buildAttributeStatement(BaseSAML2ProfileRequestContext<?,?,?> requestContext)
364 throws ProfileException {
365 if (log.isDebugEnabled()) {
366 log.debug("Creating attribute statement in response to SAML request "
367 + requestContext.getInboundSAMLMessageId() + " from relying party "
368 + requestContext.getRelyingPartyEntityId());
370 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
371 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
373 if (requestContext.getInboundSAMLMessage() instanceof AttributeQuery) {
374 return attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext.getInboundSAMLMessage(),
375 requestContext.getPrincipalAttributes().values());
377 return attributeAuthority.buildAttributeStatement(null, requestContext.getPrincipalAttributes().values());
379 } catch (AttributeRequestException e) {
380 log.error("Error encoding attributes for principal " + requestContext.getPrincipalName(), e);
381 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
382 throw new ProfileException("Error encoding attributes for principal " + requestContext.getPrincipalName(), e);
387 * Resolves the principal name of the subject of the request.
389 * @param requestContext current request context
391 * @throws ProfileException thrown if the principal name can not be resolved
393 protected void resolvePrincipal(BaseSAML2ProfileRequestContext<RequestAbstractType, StatusResponseType, AbstractSAML2ProfileConfiguration> requestContext) throws ProfileException {
394 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
395 if (profileConfiguration == null) {
396 log.error("Unable to resolve principal, no SAML 2 profile configuration for relying party "
397 + requestContext.getRelyingPartyEntityId());
398 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
399 "Error resolving principal"));
400 throw new ProfileException(
401 "Unable to resolve principal, no SAML 2 profile configuration for relying party "
402 + requestContext.getRelyingPartyEntityId());
404 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
406 if (log.isDebugEnabled()) {
407 log.debug("Resolving principal name for subject of SAML request " + requestContext.getInboundSAMLMessageId()
408 + " from relying party " + requestContext.getRelyingPartyEntityId());
412 String principal = attributeAuthority.getPrincipal(requestContext);
413 requestContext.setPrincipalName(principal);
414 } catch (AttributeRequestException e) {
415 log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
416 + " from relying party " + requestContext.getRelyingPartyEntityId(), e);
417 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.UNKNOWN_PRINCIPAL_URI,
418 "Error resolving principal"));
419 throw new ProfileException("Error resolving attributes for SAML request "
420 + requestContext.getInboundSAMLMessageId() + " from relying party "
421 + requestContext.getRelyingPartyEntityId(), e);
426 * Signs the given assertion if either the current profile configuration or the relying party configuration contains
427 * signing credentials.
429 * @param requestContext current request context
430 * @param assertion assertion to sign
432 * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
433 * required, if a signing credential is not configured
435 protected void signAssertion(BaseSAML2ProfileRequestContext<?,?,?> requestContext, Assertion assertion)
436 throws ProfileException {
437 if (log.isDebugEnabled()) {
438 log.debug("Determining if SAML assertion to relying party " + requestContext.getRelyingPartyEntityId()
439 + " should be signed");
442 boolean signAssertion = false;
444 AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
446 if (requestContext.getRelyingPartyRoleMetadata() instanceof SPSSODescriptor) {
447 SPSSODescriptor ssoDescriptor = (SPSSODescriptor) requestContext.getRelyingPartyRoleMetadata();
448 if (ssoDescriptor.getWantAssertionsSigned() != null) {
449 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
450 if (log.isDebugEnabled()) {
451 log.debug("Entity metadata for relying party " + requestContext.getRelyingPartyEntityId()
452 + " indicates to sign assertions: " + signAssertion);
455 } else if (profileConfig.getSignAssertions()) {
456 signAssertion = true;
457 log.debug("IdP relying party configuration "
458 + requestContext.getRelyingPartyConfiguration().getRelyingPartyId()
459 + " indicates to sign assertions: " + signAssertion);
462 if (!signAssertion) {
466 if (log.isDebugEnabled()) {
467 log.debug("Determining signing credntial for assertion to relying party "
468 + requestContext.getRelyingPartyEntityId());
470 Credential signatureCredential = profileConfig.getSigningCredential();
471 if (signatureCredential == null) {
472 signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
475 if (signatureCredential == null) {
476 throw new ProfileException("No signing credential is specified for relying party configuration "
477 + requestContext.getRelyingPartyConfiguration().getProviderId()
478 + " or it's SAML2 attribute query profile configuration");
481 if (log.isDebugEnabled()) {
482 log.debug("Signing assertion to relying party " + requestContext.getRelyingPartyEntityId());
484 SAMLObjectContentReference contentRef = new SAMLObjectContentReference(assertion);
485 Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
486 signature.getContentReferences().add(contentRef);
487 assertion.setSignature(signature);
489 Signer.signObject(signature);
493 * Build a status message, with an optional second-level failure message.
495 * @param topLevelCode The top-level status code. Should be from saml-core-2.0-os, sec. 3.2.2.2
496 * @param secondLevelCode An optional second-level failure code. Should be from saml-core-2.0-is, sec 3.2.2.2. If
497 * null, no second-level Status element will be set.
498 * @param failureMessage An optional second-level failure message
500 * @return a Status object.
502 protected Status buildStatus(String topLevelCode, String secondLevelCode, String failureMessage) {
503 Status status = statusBuilder.buildObject();
505 StatusCode statusCode = statusCodeBuilder.buildObject();
506 statusCode.setValue(DatatypeHelper.safeTrimOrNullString(topLevelCode));
507 status.setStatusCode(statusCode);
509 if (secondLevelCode != null) {
510 StatusCode secondLevelStatusCode = statusCodeBuilder.buildObject();
511 secondLevelStatusCode.setValue(DatatypeHelper.safeTrimOrNullString(secondLevelCode));
512 statusCode.setStatusCode(secondLevelStatusCode);
515 if (failureMessage != null) {
516 StatusMessage msg = statusMessageBuilder.buildObject();
517 msg.setMessage(failureMessage);
518 status.setStatusMessage(msg);
525 * Builds the SAML subject for the user for the service provider.
527 * @param requestContext current request context
528 * @param confirmationMethod subject confirmation method used for the subject
529 * @param issueInstant instant the subject confirmation data should reflect for issuance
531 * @return SAML subject for the user for the service provider
533 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
534 * name ID attribute or because there are no supported name formats
536 protected Subject buildSubject(BaseSAML2ProfileRequestContext<?,?,?> requestContext, String confirmationMethod,
537 DateTime issueInstant) throws ProfileException {
538 NameID nameID = buildNameId(requestContext);
539 requestContext.setSubjectNameID(nameID);
540 // TODO handle encryption
542 SubjectConfirmationData confirmationData = subjectConfirmationDataBuilder.buildObject();
543 HTTPInTransport inTransport = (HTTPInTransport) requestContext.getMessageInTransport();
544 confirmationData.setAddress(inTransport.getPeerAddress());
545 confirmationData.setInResponseTo(requestContext.getInboundSAMLMessageId());
546 confirmationData.setNotOnOrAfter(issueInstant.plus(requestContext.getProfileConfiguration()
547 .getAssertionLifetime()));
549 Endpoint relyingPartyEndpoint = requestContext.getRelyingPartyEndpoint();
550 if (relyingPartyEndpoint != null) {
551 if (relyingPartyEndpoint.getResponseLocation() != null) {
552 confirmationData.setRecipient(relyingPartyEndpoint.getResponseLocation());
554 confirmationData.setRecipient(relyingPartyEndpoint.getLocation());
558 SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
559 subjectConfirmation.setMethod(confirmationMethod);
560 subjectConfirmation.setSubjectConfirmationData(confirmationData);
562 Subject subject = subjectBuilder.buildObject();
563 subject.setNameID(nameID);
564 subject.getSubjectConfirmations().add(subjectConfirmation);
570 * Builds a NameID appropriate for this request. NameIDs are built by inspecting the SAML request and metadata,
571 * picking a name format that was requested by the relying party or is mutually supported by both the relying party
572 * and asserting party as described in their metadata entries. Once a set of supported name formats is determined
573 * the principals attributes are inspected for an attribute supported an attribute encoder whose category is one of
574 * the supported name formats.
576 * @param requestContext current request context
578 * @return the NameID appropriate for this request
580 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
581 * name ID attribute or because there are no supported name formats
583 protected NameID buildNameId(BaseSAML2ProfileRequestContext<?,?,?> requestContext) throws ProfileException {
584 if (log.isDebugEnabled()) {
585 log.debug("Building assertion NameID for principal/relying party:" + requestContext.getPrincipalName()
586 + "/" + requestContext.getRelyingPartyEntityId());
588 Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
589 List<String> supportedNameFormats = getNameFormats(requestContext);
591 if (log.isDebugEnabled()) {
592 log.debug("Supported NameID formats: " + supportedNameFormats);
595 if (principalAttributes == null || supportedNameFormats == null) {
596 log.error("No attributes for principal " + requestContext.getPrincipalName()
597 + " support constructions of NameID");
598 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
599 "Unable to construct NameID"));
600 throw new ProfileException("No principal attributes support NameID construction");
604 SAML2NameIDAttributeEncoder nameIdEncoder;
605 for (BaseAttribute<?> attribute : principalAttributes.values()) {
606 for (AttributeEncoder encoder : attribute.getEncoders()) {
607 if (encoder instanceof SAML2NameIDAttributeEncoder) {
608 nameIdEncoder = (SAML2NameIDAttributeEncoder) encoder;
609 if (supportedNameFormats.contains(nameIdEncoder.getNameFormat())) {
610 if (log.isDebugEnabled()) {
611 log.debug("Using attribute " + attribute.getId() + " suppoting NameID format "
612 + nameIdEncoder.getNameFormat() + " to create the NameID for principal "
613 + requestContext.getPrincipalName());
615 return nameIdEncoder.encode(attribute);
620 log.error("No principal attribute supported encoding into a supported name ID format.");
621 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
622 throw new ProfileException("No principal attribute supported encoding into a supported name ID format.");
623 } catch (AttributeEncodingException e) {
624 log.error("Unable to encode NameID attribute", e);
625 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
626 throw new ProfileException("Unable to encode NameID attribute", e);
631 * Gets the NameID format to use when creating NameIDs for the relying party.
633 * @param requestContext current request context
635 * @return list of nameID formats that may be used with the relying party
637 * @throws ProfileException thrown if there is a problem determing the NameID format to use
639 protected List<String> getNameFormats(BaseSAML2ProfileRequestContext<?,?,?> requestContext) throws ProfileException {
640 ArrayList<String> nameFormats = new ArrayList<String>();
642 List<String> assertingPartySupportedFormats = getEntitySupportedFormats(requestContext
643 .getAssertingPartyRoleMetadata());
645 String nameFormat = null;
646 if (requestContext.getInboundSAMLMessage() instanceof AuthnRequest) {
647 AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
648 if (authnRequest.getNameIDPolicy() != null && !DatatypeHelper.isEmpty(nameFormat)) {
649 nameFormat = authnRequest.getNameIDPolicy().getFormat();
650 if (assertingPartySupportedFormats.contains(nameFormat)) {
651 nameFormats.add(nameFormat);
653 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
654 StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
655 throw new ProfileException("NameID format required by relying party is not supported");
660 if (nameFormats.isEmpty()) {
661 List<String> relyingPartySupportedFormats = getEntitySupportedFormats(requestContext
662 .getRelyingPartyRoleMetadata());
664 assertingPartySupportedFormats.retainAll(relyingPartySupportedFormats);
665 nameFormats.addAll(assertingPartySupportedFormats);
667 if (nameFormats.isEmpty()) {
668 nameFormats.add("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
675 * Gets the list of NameID formats supported for a given role.
677 * @param role the role to get the list of supported NameID formats
679 * @return list of supported NameID formats
681 protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
682 List<NameIDFormat> nameIDFormats = null;
684 if (role instanceof SSODescriptor) {
685 nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
686 } else if (role instanceof AuthnAuthorityDescriptor) {
687 nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
688 } else if (role instanceof PDPDescriptor) {
689 nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
690 } else if (role instanceof AttributeAuthorityDescriptor) {
691 nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
694 ArrayList<String> supportedFormats = new ArrayList<String>();
695 if (nameIDFormats != null) {
696 for (NameIDFormat format : nameIDFormats) {
697 supportedFormats.add(format.getFormat());
701 return supportedFormats;
705 * Constructs an SAML response message carrying a request error.
707 * @param requestContext current request context
709 * @return the constructed error response
711 protected Response buildErrorResponse(BaseSAML2ProfileRequestContext<?,?,?> requestContext) {
712 Response samlResponse = responseBuilder.buildObject();
713 samlResponse.setIssueInstant(new DateTime());
714 populateStatusResponse(requestContext, samlResponse);
716 samlResponse.setStatus(requestContext.getFailureStatus());
722 * Writes an aduit log entry indicating the successful response to the attribute request.
724 * @param context current request context
726 protected void writeAuditLogEntry(BaseSAML2ProfileRequestContext<?,?,?> context) {
727 AuditLogEntry auditLogEntry = new AuditLogEntry();
728 auditLogEntry.setMessageProfile(getProfileId());
729 auditLogEntry.setPrincipalAuthenticationMethod(context.getPrincipalAuthenticationMethod());
730 auditLogEntry.setPrincipalName(context.getPrincipalName());
731 auditLogEntry.setAssertingPartyId(context.getAssertingPartyEntityId());
732 auditLogEntry.setRelyingPartyId(context.getRelyingPartyEntityId());
733 auditLogEntry.setRequestBinding(getMessageDecoder().getBindingURI());
734 auditLogEntry.setRequestId(context.getInboundSAMLMessageId());
735 auditLogEntry.setResponseBinding(getMessageEncoder().getBindingURI());
736 auditLogEntry.setResponseId(context.getOutboundSAMLMessageId());
737 if (context.getReleasedPrincipalAttributeIds() != null) {
738 auditLogEntry.getReleasedAttributes().addAll(context.getReleasedPrincipalAttributeIds());
740 getAduitLog().log(Level.CRITICAL, auditLogEntry);