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.saml1;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.List;
24 import javax.xml.namespace.QName;
26 import org.joda.time.DateTime;
27 import org.opensaml.Configuration;
28 import org.opensaml.common.SAMLObject;
29 import org.opensaml.common.SAMLObjectBuilder;
30 import org.opensaml.common.SAMLVersion;
31 import org.opensaml.common.binding.encoding.SAMLMessageEncoder;
32 import org.opensaml.saml1.core.Assertion;
33 import org.opensaml.saml1.core.AttributeQuery;
34 import org.opensaml.saml1.core.AttributeStatement;
35 import org.opensaml.saml1.core.Audience;
36 import org.opensaml.saml1.core.AudienceRestrictionCondition;
37 import org.opensaml.saml1.core.Conditions;
38 import org.opensaml.saml1.core.ConfirmationMethod;
39 import org.opensaml.saml1.core.NameIdentifier;
40 import org.opensaml.saml1.core.RequestAbstractType;
41 import org.opensaml.saml1.core.Response;
42 import org.opensaml.saml1.core.ResponseAbstractType;
43 import org.opensaml.saml1.core.Statement;
44 import org.opensaml.saml1.core.Status;
45 import org.opensaml.saml1.core.StatusCode;
46 import org.opensaml.saml1.core.StatusMessage;
47 import org.opensaml.saml1.core.Subject;
48 import org.opensaml.saml1.core.SubjectConfirmation;
49 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
50 import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor;
51 import org.opensaml.saml2.metadata.NameIDFormat;
52 import org.opensaml.saml2.metadata.PDPDescriptor;
53 import org.opensaml.saml2.metadata.RoleDescriptor;
54 import org.opensaml.saml2.metadata.SPSSODescriptor;
55 import org.opensaml.saml2.metadata.SSODescriptor;
56 import org.opensaml.ws.message.encoder.MessageEncodingException;
57 import org.opensaml.xml.XMLObjectBuilder;
58 import org.opensaml.xml.io.Marshaller;
59 import org.opensaml.xml.io.MarshallingException;
60 import org.opensaml.xml.security.SecurityException;
61 import org.opensaml.xml.security.SecurityHelper;
62 import org.opensaml.xml.security.credential.Credential;
63 import org.opensaml.xml.signature.Signature;
64 import org.opensaml.xml.signature.SignatureException;
65 import org.opensaml.xml.signature.Signer;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
69 import edu.internet2.middleware.shibboleth.common.attribute.AttributeRequestException;
70 import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
71 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncoder;
72 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncodingException;
73 import edu.internet2.middleware.shibboleth.common.attribute.encoding.SAML1NameIdentifierEncoder;
74 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML1AttributeAuthority;
75 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
76 import edu.internet2.middleware.shibboleth.common.profile.provider.BaseSAMLProfileRequestContext;
77 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.CryptoOperationRequirementLevel;
78 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.AbstractSAML1ProfileConfiguration;
79 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
80 import edu.internet2.middleware.shibboleth.idp.session.Session;
82 /** Common implementation details for profile handlers. */
83 public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHandler {
85 /** SAML Version for this profile handler. */
86 public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_11;
89 private static Logger log = LoggerFactory.getLogger(AbstractSAML1ProfileHandler.class);
91 /** Builder of Response objects. */
92 private SAMLObjectBuilder<Response> responseBuilder;
94 /** Builder of Assertion objects. */
95 private SAMLObjectBuilder<Assertion> assertionBuilder;
97 /** Builder of Conditions objects. */
98 private SAMLObjectBuilder<Conditions> conditionsBuilder;
100 /** Builder of AudienceRestrictionCondition objects. */
101 private SAMLObjectBuilder<AudienceRestrictionCondition> audienceRestrictionConditionBuilder;
103 /** Builder of AudienceRestrictionCondition objects. */
104 private SAMLObjectBuilder<Audience> audienceBuilder;
106 /** Builder of SubjectConfirmation objects. */
107 private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
109 /** Builder of ConfirmationMethod objects. */
110 private SAMLObjectBuilder<ConfirmationMethod> confirmationMethodBuilder;
112 /** Builder of Subject objects. */
113 private SAMLObjectBuilder<Subject> subjectBuilder;
115 /** Builder for Status objects. */
116 private SAMLObjectBuilder<Status> statusBuilder;
118 /** Builder for StatusCode objects. */
119 private SAMLObjectBuilder<StatusCode> statusCodeBuilder;
121 /** Builder for StatusMessage objects. */
122 private SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
124 /** For building signature. */
125 private XMLObjectBuilder<Signature> signatureBuilder;
128 * Default constructor.
130 @SuppressWarnings("unchecked")
131 public AbstractSAML1ProfileHandler() {
133 responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
134 assertionBuilder = (SAMLObjectBuilder<Assertion>) getBuilderFactory()
135 .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
136 conditionsBuilder = (SAMLObjectBuilder<Conditions>) getBuilderFactory().getBuilder(
137 Conditions.DEFAULT_ELEMENT_NAME);
138 audienceRestrictionConditionBuilder = (SAMLObjectBuilder<AudienceRestrictionCondition>) getBuilderFactory()
139 .getBuilder(AudienceRestrictionCondition.DEFAULT_ELEMENT_NAME);
140 audienceBuilder = (SAMLObjectBuilder<Audience>) getBuilderFactory().getBuilder(Audience.DEFAULT_ELEMENT_NAME);
141 subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) getBuilderFactory().getBuilder(
142 SubjectConfirmation.DEFAULT_ELEMENT_NAME);
143 confirmationMethodBuilder = (SAMLObjectBuilder<ConfirmationMethod>) getBuilderFactory().getBuilder(
144 ConfirmationMethod.DEFAULT_ELEMENT_NAME);
145 subjectBuilder = (SAMLObjectBuilder<Subject>) getBuilderFactory().getBuilder(Subject.DEFAULT_ELEMENT_NAME);
146 statusBuilder = (SAMLObjectBuilder<Status>) getBuilderFactory().getBuilder(Status.DEFAULT_ELEMENT_NAME);
147 statusCodeBuilder = (SAMLObjectBuilder<StatusCode>) getBuilderFactory().getBuilder(
148 StatusCode.DEFAULT_ELEMENT_NAME);
149 statusMessageBuilder = (SAMLObjectBuilder<StatusMessage>) getBuilderFactory().getBuilder(
150 StatusMessage.DEFAULT_ELEMENT_NAME);
151 signatureBuilder = (XMLObjectBuilder<Signature>) getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
155 protected void populateRequestContext(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
156 BaseSAML1ProfileRequestContext saml1Request = (BaseSAML1ProfileRequestContext) requestContext;
158 super.populateRequestContext(requestContext);
159 } catch (ProfileException e) {
160 if (saml1Request.getFailureStatus() == null) {
161 saml1Request.setFailureStatus(buildStatus(StatusCode.REQUESTER, null, e.getMessage()));
168 * Populates the request context with the information about the user.
170 * This method requires the the following request context properties to be populated: inbound message transport,
173 * This methods populates the following request context properties: user's session, user's principal name, and
174 * service authentication method
176 * @param requestContext current request context
178 protected void populateUserInformation(BaseSAMLProfileRequestContext requestContext) {
179 Session userSession = getUserSession(requestContext.getInboundMessageTransport());
180 if (userSession == null) {
181 NameIdentifier subject = (NameIdentifier) requestContext.getSubjectNameIdentifier();
182 if (subject != null && subject.getNameIdentifier() != null) {
183 userSession = getUserSession(subject.getNameIdentifier());
187 if (userSession != null) {
188 requestContext.setUserSession(userSession);
189 requestContext.setPrincipalName(userSession.getPrincipalName());
190 requestContext.setPrincipalAuthenticationMethod(userSession.getServicesInformation().get(
191 requestContext.getPeerEntityId()).getAuthenticationMethod().getAuthenticationMethod());
196 * Checks that the SAML major version for a request is 1.
198 * @param requestContext current request context containing the SAML message
200 * @throws ProfileException thrown if the major version of the SAML request is not 1
202 protected void checkSamlVersion(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
203 SAMLObject samlObject = requestContext.getInboundSAMLMessage();
205 if (samlObject instanceof RequestAbstractType) {
206 RequestAbstractType request = (RequestAbstractType) samlObject;
207 if (request.getMajorVersion() < 1) {
208 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER, StatusCode.REQUEST_VERSION_TOO_LOW,
210 throw new ProfileException("SAML request major version too low");
211 } else if (request.getMajorVersion() > 1) {
212 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER, StatusCode.REQUEST_VERSION_TOO_HIGH,
214 throw new ProfileException("SAML request major version too low");
220 * Builds a response to the attribute query within the request context.
222 * @param requestContext current request context
223 * @param statements the statements to include in the response
225 * @return the built response
227 * @throws ProfileException thrown if there is a problem creating the SAML response
229 protected Response buildResponse(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, List<Statement> statements)
230 throws ProfileException {
232 DateTime issueInstant = new DateTime();
234 // create the assertion and add the attribute statement
235 Assertion assertion = buildAssertion(requestContext, issueInstant);
236 if (statements != null && !statements.isEmpty()) {
237 assertion.getStatements().addAll(statements);
240 // create the SAML response and add the assertion
241 Response samlResponse = responseBuilder.buildObject();
242 samlResponse.setIssueInstant(issueInstant);
243 populateStatusResponse(requestContext, samlResponse);
245 samlResponse.getAssertions().add(assertion);
247 // sign the assertion if it should be signed
248 signAssertion(requestContext, assertion);
250 Status status = buildStatus(StatusCode.SUCCESS, null, null);
251 samlResponse.setStatus(status);
257 * Builds a basic assertion with its id, issue instant, SAML version, issuer, subject, and conditions populated.
259 * @param requestContext current request context
260 * @param issueInstant time to use as assertion issue instant
262 * @return the built assertion
264 protected Assertion buildAssertion(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
265 Assertion assertion = assertionBuilder.buildObject();
266 assertion.setID(getIdGenerator().generateIdentifier());
267 assertion.setIssueInstant(issueInstant);
268 assertion.setVersion(SAMLVersion.VERSION_11);
269 assertion.setIssuer(requestContext.getLocalEntityId());
271 Conditions conditions = buildConditions(requestContext, issueInstant);
272 assertion.setConditions(conditions);
278 * Builds a SAML assertion condition set. The following fields are set; not before, not on or after, audience
279 * restrictions, and proxy restrictions.
281 * @param requestContext current request context
282 * @param issueInstant timestamp the assertion was created
284 * @return constructed conditions
286 protected Conditions buildConditions(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
287 AbstractSAML1ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
289 Conditions conditions = conditionsBuilder.buildObject();
290 conditions.setNotBefore(issueInstant);
291 conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
293 Collection<String> audiences;
295 // add audience restrictions
296 audiences = profileConfig.getAssertionAudiences();
297 if (audiences != null && audiences.size() > 0) {
298 AudienceRestrictionCondition audienceRestriction = audienceRestrictionConditionBuilder.buildObject();
299 for (String audienceUri : audiences) {
300 Audience audience = audienceBuilder.buildObject();
301 audience.setUri(audienceUri);
302 audienceRestriction.getAudiences().add(audience);
304 conditions.getAudienceRestrictionConditions().add(audienceRestriction);
311 * Builds the SAML subject for the user for the service provider.
313 * @param requestContext current request context
314 * @param confirmationMethod subject confirmation method used for the subject
316 * @return SAML subject for the user for the service provider
318 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
319 * name ID attribute or because there are no supported name formats
321 protected Subject buildSubject(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, String confirmationMethod)
322 throws ProfileException {
323 NameIdentifier nameID = buildNameId(requestContext);
324 requestContext.setSubjectNameIdentifier(nameID);
326 ConfirmationMethod method = confirmationMethodBuilder.buildObject();
327 method.setConfirmationMethod(confirmationMethod);
329 SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
330 subjectConfirmation.getConfirmationMethods().add(method);
332 Subject subject = subjectBuilder.buildObject();
333 subject.setNameIdentifier(nameID);
334 subject.setSubjectConfirmation(subjectConfirmation);
340 * Builds a NameIdentifier appropriate for this request. NameIdentifier are built by inspecting the SAML request and
341 * metadata, picking a name format that was requested by the relying party or is mutually supported by both the
342 * relying party and asserting party as described in their metadata entries. Once a set of supported name formats is
343 * determined the principals attributes are inspected for an attribute supported an attribute encoder whose category
344 * is one of the supported name formats.
346 * @param requestContext current request context
348 * @return the NameIdentifier appropriate for this request
350 * @throws ProfileException thrown if a NameIdentifier can not be created either because there was a problem
351 * encoding the name ID attribute or because there are no supported name formats
353 protected NameIdentifier buildNameId(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext)
354 throws ProfileException {
355 log.debug("Building assertion NameIdentifier to relying party {} for principal {}", requestContext
356 .getInboundMessageIssuer(), requestContext.getPrincipalName());
357 Map<String, BaseAttribute> principalAttributes = requestContext.getAttributes();
358 if (principalAttributes == null || principalAttributes.isEmpty()) {
359 log.error("No attributes for principal {}, unable to construct of NameID", requestContext
360 .getPrincipalName());
361 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
362 "Unable to construct NameIdentifier"));
363 throw new ProfileException("No principal attributes support NameIdentifier construction");
366 List<String> supportedNameFormats = getNameFormats(requestContext);
367 if (supportedNameFormats == null || supportedNameFormats.isEmpty()) {
368 log.error("No common NameID formats supported by SP {} and IdP", requestContext.getInboundMessageIssuer());
369 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
370 "Unable to construct NameIdentifier"));
371 throw new ProfileException("No principal attributes support NameIdentifier construction");
374 log.debug("Supported name formats: {}", supportedNameFormats);
376 SAML1NameIdentifierEncoder nameIdEncoder;
378 for (BaseAttribute<?> attribute : principalAttributes.values()) {
379 for (AttributeEncoder encoder : attribute.getEncoders()) {
380 if (encoder instanceof SAML1NameIdentifierEncoder) {
381 nameIdEncoder = (SAML1NameIdentifierEncoder) encoder;
382 if (supportedNameFormats.contains(nameIdEncoder.getNameFormat())) {
385 "Using attribute {} suppoting name format {} to create the NameIdentifier for principal",
386 attribute.getId(), nameIdEncoder.getNameFormat());
387 return nameIdEncoder.encode(attribute);
392 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
393 "Unable to construct NameIdentifier"));
394 log.error("No principal attribute supports an encoding into a supported name ID format.");
395 throw new ProfileException("No principal attribute supports an encoding into a supported name ID format.");
396 } catch (AttributeEncodingException e) {
397 log.error("Unable to construct NameIdentifier", e);
398 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
399 "Unable to construct NameIdentifier"));
400 throw new ProfileException("Unable to encode NameIdentifier attribute", e);
406 * Gets the NameIdentifier format to use when creating NameIdentifiers for the relying party.
408 * @param requestContext current request context
410 * @return list of formats that may be used with the relying party
412 * @throws ProfileException thrown if there is a problem determining the NameIdentifier format to use
414 protected List<String> getNameFormats(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext)
415 throws ProfileException {
416 ArrayList<String> nameFormats = new ArrayList<String>();
418 RoleDescriptor relyingPartyRole = requestContext.getPeerEntityRoleMetadata();
419 if (relyingPartyRole != null) {
420 List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
421 if (relyingPartySupportedFormats != null && !relyingPartySupportedFormats.isEmpty()) {
422 nameFormats.addAll(relyingPartySupportedFormats);
424 RoleDescriptor assertingPartyRole = requestContext.getLocalEntityRoleMetadata();
425 if (assertingPartyRole != null) {
426 List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
427 if (assertingPartySupportedFormats != null && !assertingPartySupportedFormats.isEmpty()) {
428 nameFormats.retainAll(assertingPartySupportedFormats);
434 if (nameFormats.isEmpty()) {
435 nameFormats.add("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified");
442 * Gets the list of NameIdentifier formats supported for a given role.
444 * @param role the role to get the list of supported NameIdentifier formats
446 * @return list of supported NameIdentifier formats
448 protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
449 List<NameIDFormat> nameIDFormats = null;
451 if (role instanceof SSODescriptor) {
452 nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
453 } else if (role instanceof AuthnAuthorityDescriptor) {
454 nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
455 } else if (role instanceof PDPDescriptor) {
456 nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
457 } else if (role instanceof AttributeAuthorityDescriptor) {
458 nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
461 ArrayList<String> supportedFormats = new ArrayList<String>();
462 if (nameIDFormats != null) {
463 for (NameIDFormat format : nameIDFormats) {
464 supportedFormats.add(format.getFormat());
468 return supportedFormats;
472 * Constructs an SAML response message carrying a request error.
474 * @param requestContext current request context containing the failure status
476 * @return the constructed error response
478 protected Response buildErrorResponse(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) {
479 Response samlResponse = responseBuilder.buildObject();
480 samlResponse.setIssueInstant(new DateTime());
481 populateStatusResponse(requestContext, samlResponse);
483 samlResponse.setStatus(requestContext.getFailureStatus());
489 * Populates the response's id, in response to, issue instant, version, and issuer properties.
491 * @param requestContext current request context
492 * @param response the response to populate
494 protected void populateStatusResponse(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext,
495 ResponseAbstractType response) {
496 response.setID(getIdGenerator().generateIdentifier());
498 SAMLObject samlMessage = requestContext.getInboundSAMLMessage();
499 if (samlMessage != null && samlMessage instanceof RequestAbstractType) {
500 response.setInResponseTo(((RequestAbstractType) samlMessage).getID());
502 response.setVersion(SAMLVersion.VERSION_11);
506 * Build a status message, with an optional second-level failure message.
508 * @param topLevelCode top-level status code
509 * @param secondLevelCode second-level status code
510 * @param failureMessage An optional second-level failure message
512 * @return a Status object.
514 protected Status buildStatus(QName topLevelCode, QName secondLevelCode, String failureMessage) {
515 Status status = statusBuilder.buildObject();
517 StatusCode statusCode = statusCodeBuilder.buildObject();
518 statusCode.setValue(topLevelCode);
519 status.setStatusCode(statusCode);
521 if (secondLevelCode != null) {
522 StatusCode secondLevelStatusCode = statusCodeBuilder.buildObject();
523 secondLevelStatusCode.setValue(secondLevelCode);
524 statusCode.setStatusCode(secondLevelStatusCode);
527 if (failureMessage != null) {
528 StatusMessage msg = statusMessageBuilder.buildObject();
529 msg.setMessage(failureMessage);
530 status.setStatusMessage(msg);
537 * Resolved the attributes for the principal.
539 * @param requestContext current request context
541 * @throws ProfileException thrown if attributes can not be resolved
543 protected void resolveAttributes(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
544 AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
545 SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
548 log.debug("Resolving attributes for principal {} of SAML request from relying party {}", requestContext
549 .getPrincipalName(), requestContext.getInboundMessageIssuer());
550 Map<String, BaseAttribute> principalAttributes = attributeAuthority.getAttributes(requestContext);
552 requestContext.setAttributes(principalAttributes);
553 } catch (AttributeRequestException e) {
554 log.error("Error resolving attributes for SAML request from relying party "
555 + requestContext.getInboundMessageIssuer(), e);
556 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error resolving attributes"));
557 throw new ProfileException("Error resolving attributes for SAML request from relying party "
558 + requestContext.getInboundMessageIssuer(), e);
563 * Executes a query for attributes and builds a SAML attribute statement from the results.
565 * @param requestContext current request context
566 * @param subjectConfMethod subject confirmation method
568 * @return attribute statement resulting from the query
570 * @throws ProfileException thrown if there is a problem making the query
572 protected AttributeStatement buildAttributeStatement(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext,
573 String subjectConfMethod) throws ProfileException {
575 log.debug("Creating attribute statement in response to SAML request from relying party {}", requestContext
576 .getInboundMessageIssuer());
577 AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
578 SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
581 AttributeStatement statment;
582 if (requestContext.getInboundSAMLMessage() instanceof AttributeQuery) {
583 statment = attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext
584 .getInboundSAMLMessage(), requestContext.getAttributes().values());
586 statment = attributeAuthority.buildAttributeStatement(null, requestContext.getAttributes().values());
589 if (statment != null) {
590 Subject statementSubject = buildSubject(requestContext, subjectConfMethod);
591 statment.setSubject(statementSubject);
595 } catch (AttributeRequestException e) {
596 log.error("Error encoding attributes for principal " + requestContext.getPrincipalName(), e);
597 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error resolving attributes"));
598 throw new ProfileException("Error encoding attributes for principal " + requestContext.getPrincipalName(),
604 * Resolves the principal name of the subject of the request.
606 * @param requestContext current request context
608 * @throws ProfileException thrown if the principal name can not be resolved
610 protected void resolvePrincipal(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
611 AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
612 SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
614 log.debug("Resolving principal name for subject of SAML request from relying party {}", requestContext
615 .getInboundMessageIssuer());
618 String principal = attributeAuthority.getPrincipal(requestContext);
619 requestContext.setPrincipalName(principal);
620 } catch (AttributeRequestException e) {
621 log.error("Error resolving attributes for SAML request from relying party "
622 + requestContext.getInboundMessageIssuer(), e);
623 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
624 "Error resolving principal"));
625 throw new ProfileException("Error resolving attributes for SAML request from relying party "
626 + requestContext.getInboundMessageIssuer(), e);
631 * Signs the given assertion if either the current profile configuration or the relying party configuration contains
632 * signing credentials.
634 * @param requestContext current request context
635 * @param assertion assertion to sign
637 * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
638 * required, if a signing credential is not configured
640 protected void signAssertion(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, Assertion assertion)
641 throws ProfileException {
642 log.debug("Determining if SAML assertion to relying party {} should be signed", requestContext
643 .getInboundMessageIssuer());
645 boolean signAssertion = false;
647 RoleDescriptor relyingPartyRole = requestContext.getPeerEntityRoleMetadata();
648 SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
649 AbstractSAML1ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
652 if (profileConfig.getSignAssertions() == CryptoOperationRequirementLevel.always
653 || (profileConfig.getSignAssertions() == CryptoOperationRequirementLevel.conditional && !encoder
654 .providesMessageIntegrity(requestContext))) {
655 signAssertion = true;
656 log.debug("IdP relying party configuration {} indicates to sign assertions: {}", requestContext
657 .getRelyingPartyConfiguration().getRelyingPartyId(), signAssertion);
659 } catch (MessageEncodingException e) {
660 log.error("Unable to determine if outbound encoding {} can provide integrity", encoder.getBindingURI());
661 throw new ProfileException("Unable to determine if outbound message should be signed");
664 if (!signAssertion && relyingPartyRole instanceof SPSSODescriptor) {
665 SPSSODescriptor ssoDescriptor = (SPSSODescriptor) relyingPartyRole;
666 if (ssoDescriptor.getWantAssertionsSigned() != null) {
667 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
668 log.debug("Entity metadata for relying party {} indicates to sign assertions: {}", requestContext
669 .getInboundMessageIssuer(), signAssertion);
673 if (!signAssertion) {
677 log.debug("Determining signing credntial for assertion to relying party {}", requestContext
678 .getInboundMessageIssuer());
679 Credential signatureCredential = profileConfig.getSigningCredential();
680 if (signatureCredential == null) {
681 signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
684 if (signatureCredential == null) {
685 throw new ProfileException("No signing credential is specified for relying party configuration "
686 + requestContext.getRelyingPartyConfiguration().getProviderId()
687 + " or it's SAML2 attribute query profile configuration");
690 log.debug("Signing assertion to relying party {}", requestContext.getInboundMessageIssuer());
691 Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
693 signature.setSigningCredential(signatureCredential);
695 // TODO pull SecurityConfiguration from SAMLMessageContext? needs to be added
696 // TODO how to pull what keyInfoGenName to use?
697 SecurityHelper.prepareSignatureParams(signature, signatureCredential, null, null);
698 } catch (SecurityException e) {
699 throw new ProfileException("Error preparing signature for signing", e);
702 assertion.setSignature(signature);
704 Marshaller assertionMarshaller = Configuration.getMarshallerFactory().getMarshaller(assertion);
706 assertionMarshaller.marshall(assertion);
707 Signer.signObject(signature);
708 } catch (MarshallingException e) {
709 log.error("Unable to marshall assertion for signing", e);
710 throw new ProfileException("Unable to marshall assertion for signing", e);
711 } catch (SignatureException e) {
712 log.error("Unable to sign assertion", e);
713 throw new ProfileException("Unable to sign assertion", e);