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.servlet.ServletRequest;
25 import javax.servlet.ServletResponse;
26 import javax.xml.namespace.QName;
28 import org.apache.log4j.Logger;
29 import org.joda.time.DateTime;
30 import org.opensaml.common.SAMLObject;
31 import org.opensaml.common.SAMLObjectBuilder;
32 import org.opensaml.common.SAMLVersion;
33 import org.opensaml.common.impl.SAMLObjectContentReference;
34 import org.opensaml.log.Level;
35 import org.opensaml.saml1.core.Assertion;
36 import org.opensaml.saml1.core.AttributeQuery;
37 import org.opensaml.saml1.core.AttributeStatement;
38 import org.opensaml.saml1.core.Audience;
39 import org.opensaml.saml1.core.AudienceRestrictionCondition;
40 import org.opensaml.saml1.core.Conditions;
41 import org.opensaml.saml1.core.ConfirmationMethod;
42 import org.opensaml.saml1.core.NameIdentifier;
43 import org.opensaml.saml1.core.Request;
44 import org.opensaml.saml1.core.RequestAbstractType;
45 import org.opensaml.saml1.core.Response;
46 import org.opensaml.saml1.core.ResponseAbstractType;
47 import org.opensaml.saml1.core.Statement;
48 import org.opensaml.saml1.core.Status;
49 import org.opensaml.saml1.core.StatusCode;
50 import org.opensaml.saml1.core.StatusMessage;
51 import org.opensaml.saml1.core.Subject;
52 import org.opensaml.saml1.core.SubjectConfirmation;
53 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
54 import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor;
55 import org.opensaml.saml2.metadata.NameIDFormat;
56 import org.opensaml.saml2.metadata.PDPDescriptor;
57 import org.opensaml.saml2.metadata.RoleDescriptor;
58 import org.opensaml.saml2.metadata.SPSSODescriptor;
59 import org.opensaml.saml2.metadata.SSODescriptor;
60 import org.opensaml.xml.XMLObjectBuilder;
61 import org.opensaml.xml.security.credential.Credential;
62 import org.opensaml.xml.signature.Signature;
63 import org.opensaml.xml.signature.Signer;
65 import edu.internet2.middleware.shibboleth.common.attribute.AttributeRequestException;
66 import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
67 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncoder;
68 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncodingException;
69 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML1AttributeAuthority;
70 import edu.internet2.middleware.shibboleth.common.attribute.provider.ShibbolethSAMLAttributeRequestContext;
71 import edu.internet2.middleware.shibboleth.common.log.AuditLogEntry;
72 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
73 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
74 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
75 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.AbstractSAML1ProfileConfiguration;
76 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
77 import edu.internet2.middleware.shibboleth.idp.session.ServiceInformation;
78 import edu.internet2.middleware.shibboleth.idp.session.Session;
80 /** Common implementation details for profile handlers. */
81 public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHandler {
83 /** SAML Version for this profile handler. */
84 public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_11;
87 private static Logger log = Logger.getLogger(AbstractSAML1ProfileHandler.class);
89 /** Builder of Response objects. */
90 private SAMLObjectBuilder<Response> responseBuilder;
92 /** Builder of Assertion objects. */
93 private SAMLObjectBuilder<Assertion> assertionBuilder;
95 /** Builder of Conditions objects. */
96 private SAMLObjectBuilder<Conditions> conditionsBuilder;
98 /** Builder of AudienceRestrictionCondition objects. */
99 private SAMLObjectBuilder<AudienceRestrictionCondition> audienceRestrictionConditionBuilder;
101 /** Builder of AudienceRestrictionCondition objects. */
102 private SAMLObjectBuilder<Audience> audienceBuilder;
104 /** Builder of NameIdentifier objects. */
105 private SAMLObjectBuilder<NameIdentifier> nameIdBuilder;
107 /** Builder of SubjectConfirmation objects. */
108 private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
110 /** Builder of ConfirmationMethod objects. */
111 private SAMLObjectBuilder<ConfirmationMethod> confirmationMethodBuilder;
113 /** Builder of Subject objects. */
114 private SAMLObjectBuilder<Subject> subjectBuilder;
116 /** Builder for Status objects. */
117 private SAMLObjectBuilder<Status> statusBuilder;
119 /** Builder for StatusCode objects. */
120 private SAMLObjectBuilder<StatusCode> statusCodeBuilder;
122 /** Builder for StatusMessage objects. */
123 private SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
125 /** For building signature. */
126 private XMLObjectBuilder<Signature> signatureBuilder;
129 * Default constructor.
131 @SuppressWarnings("unchecked")
132 public AbstractSAML1ProfileHandler() {
134 responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
135 assertionBuilder = (SAMLObjectBuilder<Assertion>) getBuilderFactory()
136 .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
137 conditionsBuilder = (SAMLObjectBuilder<Conditions>) getBuilderFactory().getBuilder(
138 Conditions.DEFAULT_ELEMENT_NAME);
139 audienceRestrictionConditionBuilder = (SAMLObjectBuilder<AudienceRestrictionCondition>) getBuilderFactory()
140 .getBuilder(AudienceRestrictionCondition.DEFAULT_ELEMENT_NAME);
141 audienceBuilder = (SAMLObjectBuilder<Audience>) getBuilderFactory().getBuilder(Audience.DEFAULT_ELEMENT_NAME);
142 nameIdBuilder = (SAMLObjectBuilder<NameIdentifier>) getBuilderFactory().getBuilder(
143 NameIdentifier.DEFAULT_ELEMENT_NAME);
144 subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) getBuilderFactory().getBuilder(
145 SubjectConfirmation.DEFAULT_ELEMENT_NAME);
146 confirmationMethodBuilder = (SAMLObjectBuilder<ConfirmationMethod>) getBuilderFactory().getBuilder(
147 ConfirmationMethod.DEFAULT_ELEMENT_NAME);
148 subjectBuilder = (SAMLObjectBuilder<Subject>) getBuilderFactory().getBuilder(Subject.DEFAULT_ELEMENT_NAME);
149 statusBuilder = (SAMLObjectBuilder<Status>) getBuilderFactory().getBuilder(Status.DEFAULT_ELEMENT_NAME);
150 statusCodeBuilder = (SAMLObjectBuilder<StatusCode>) getBuilderFactory().getBuilder(
151 StatusCode.DEFAULT_ELEMENT_NAME);
152 statusMessageBuilder = (SAMLObjectBuilder<StatusMessage>) getBuilderFactory().getBuilder(
153 StatusMessage.DEFAULT_ELEMENT_NAME);
154 signatureBuilder = (XMLObjectBuilder<Signature>) getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
158 * Convenience method for getting the SAML 1 Response builder.
160 * @return SAML 1 Response builder
162 public SAMLObjectBuilder<Response> getResponseBuilder() {
163 return responseBuilder;
167 * Convenience method for getting the SAML 1 Assertion builder.
169 * @return SAML 1 Assertion builder
171 public SAMLObjectBuilder<Assertion> getAssertionBuilder() {
172 return assertionBuilder;
176 * Convenience method for getting the SAML 1 Conditions builder.
178 * @return SAML 1 Conditions builder
180 public SAMLObjectBuilder<Conditions> getConditionsBuilder() {
181 return conditionsBuilder;
185 * Convenience method for getting the SAML 1 AudienceRestrictionCondition builder.
187 * @return SAML 1 AudienceRestrictionCondition builder
189 public SAMLObjectBuilder<AudienceRestrictionCondition> getAudienceRestrictionConditionBuilder() {
190 return audienceRestrictionConditionBuilder;
194 * Convenience method for getting the SAML 1 Audience builder.
196 * @return SAML 1 Audience builder
198 public SAMLObjectBuilder<Audience> getAudienceBuilder() {
199 return audienceBuilder;
203 * Convenience method for getting the SAML 1 NameIdentifier builder.
205 * @return SAML 1 NameIdentifier builder
207 public SAMLObjectBuilder<NameIdentifier> getNameIdentifierBuilder() {
208 return nameIdBuilder;
212 * Convenience method for getting the SAML 1 SubjectConfirmation builder.
214 * @return SAML 1 SubjectConfirmation builder
216 public SAMLObjectBuilder<SubjectConfirmation> getSubjectConfirmationBuilder() {
217 return subjectConfirmationBuilder;
221 * Convenience method for getting the SAML 1 ConfirmationMethod builder.
223 * @return SAML 1 ConfirmationMethod builder
225 public SAMLObjectBuilder<ConfirmationMethod> getConfirmationMethodBuilder() {
226 return confirmationMethodBuilder;
230 * Convenience method for getting the SAML 1 Subject builder.
232 * @return SAML 1 Subject builder
234 public SAMLObjectBuilder<Subject> getSubjectBuilder() {
235 return subjectBuilder;
239 * Convenience method for getting the SAML 1 Status builder.
241 * @return SAML 1 Status builder
243 public SAMLObjectBuilder<Status> getStatusBuilder() {
244 return statusBuilder;
248 * Convenience method for getting the SAML 1 StatusCode builder.
250 * @return SAML 2 StatusCode builder
252 public SAMLObjectBuilder<StatusCode> getStatusCodeBuilder() {
253 return statusCodeBuilder;
257 * Convenience method for getting the SAML 1 StatusMessage builder.
259 * @return SAML StatusMessage builder
261 public SAMLObjectBuilder<StatusMessage> getStatusMessageBuilder() {
262 return statusMessageBuilder;
266 * Checks that the SAML major version for a request is 1.
268 * @param requestContext current request context containing the SAML message
270 * @throws ProfileException thrown if the major version of the SAML request is not 1
272 protected void checkSamlVersion(SAML1ProfileRequestContext requestContext) throws ProfileException {
273 SAMLObject samlObject = requestContext.getSamlRequest();
275 if (samlObject instanceof RequestAbstractType) {
276 RequestAbstractType request = (RequestAbstractType) samlObject;
277 if (request.getMajorVersion() < 1) {
278 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER, StatusCode.REQUEST_VERSION_TOO_LOW,
280 throw new ProfileException("SAML request major version too low");
281 } else if (request.getMajorVersion() > 1) {
282 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER, StatusCode.REQUEST_VERSION_TOO_HIGH,
284 throw new ProfileException("SAML request major version too low");
290 * Builds a response to the attribute query within the request context.
292 * @param requestContext current request context
293 * @param statements the statements to include in the response
295 * @return the built response
297 * @throws ProfileException thrown if there is a problem creating the SAML response
299 protected Response buildResponse(SAML1ProfileRequestContext requestContext, List<Statement> statements)
300 throws ProfileException {
302 DateTime issueInstant = new DateTime();
304 // create the assertion and add the attribute statement
305 Assertion assertion = buildAssertion(requestContext, issueInstant);
306 if (statements != null) {
307 assertion.getStatements().addAll(statements);
310 // create the SAML response and add the assertion
311 Response samlResponse = getResponseBuilder().buildObject();
312 samlResponse.setIssueInstant(issueInstant);
313 populateStatusResponse(requestContext, samlResponse);
315 samlResponse.getAssertions().add(assertion);
317 // sign the assertion if it should be signed
318 signAssertion(requestContext, assertion);
320 Status status = buildStatus(StatusCode.SUCCESS, null, null);
321 samlResponse.setStatus(status);
327 * Builds a basic assertion with its id, issue instant, SAML version, issuer, subject, and conditions populated.
329 * @param requestContext current request context
330 * @param issueInstant time to use as assertion issue instant
332 * @return the built assertion
334 protected Assertion buildAssertion(SAML1ProfileRequestContext requestContext, DateTime issueInstant) {
335 Assertion assertion = getAssertionBuilder().buildObject();
336 assertion.setID(getIdGenerator().generateIdentifier());
337 assertion.setIssueInstant(issueInstant);
338 assertion.setVersion(SAMLVersion.VERSION_11);
339 assertion.setIssuer(requestContext.getAssertingPartyId());
341 Conditions conditions = buildConditions(requestContext, issueInstant);
342 assertion.setConditions(conditions);
348 * Builds a SAML assertion condition set. The following fields are set; not before, not on or after, audience
349 * restrictions, and proxy restrictions.
351 * @param requestContext current request context
352 * @param issueInstant timestamp the assertion was created
354 * @return constructed conditions
356 protected Conditions buildConditions(SAML1ProfileRequestContext requestContext, DateTime issueInstant) {
357 AbstractSAML1ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
359 Conditions conditions = getConditionsBuilder().buildObject();
360 conditions.setNotBefore(issueInstant);
361 conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
363 Collection<String> audiences;
365 // add audience restrictions
366 audiences = profileConfig.getAssertionAudiences();
367 if (audiences != null && audiences.size() > 0) {
368 AudienceRestrictionCondition audienceRestriction = getAudienceRestrictionConditionBuilder().buildObject();
369 for (String audienceUri : audiences) {
370 Audience audience = getAudienceBuilder().buildObject();
371 audience.setUri(audienceUri);
372 audienceRestriction.getAudiences().add(audience);
374 conditions.getAudienceRestrictionConditions().add(audienceRestriction);
381 * Builds the SAML subject for the user for the service provider.
383 * @param requestContext current request context
384 * @param confirmationMethod subject confirmation method used for the subject
386 * @return SAML subject for the user for the service provider
388 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
389 * name ID attribute or because there are no supported name formats
391 protected Subject buildSubject(SAML1ProfileRequestContext requestContext, String confirmationMethod)
392 throws ProfileException {
393 NameIdentifier nameID = buildNameId(requestContext);
394 requestContext.setSubjectNameID(nameID);
396 ConfirmationMethod method = getConfirmationMethodBuilder().buildObject();
397 method.setConfirmationMethod(confirmationMethod);
399 SubjectConfirmation subjectConfirmation = getSubjectConfirmationBuilder().buildObject();
400 subjectConfirmation.getConfirmationMethods().add(method);
402 Subject subject = getSubjectBuilder().buildObject();
403 subject.setNameIdentifier(nameID);
404 subject.setSubjectConfirmation(subjectConfirmation);
410 * Builds a NameIdentifier appropriate for this request. NameIdentifier are built by inspecting the SAML request and
411 * metadata, picking a name format that was requested by the relying party or is mutually supported by both the
412 * relying party and asserting party as described in their metadata entries. Once a set of supported name formats is
413 * determined the principals attributes are inspected for an attribute supported an attribute encoder whose category
414 * is one of the supported name formats.
416 * @param requestContext current request context
418 * @return the NameIdentifier appropriate for this request
420 * @throws ProfileException thrown if a NameIdentifier can not be created either because there was a problem
421 * encoding the name ID attribute or because there are no supported name formats
423 protected NameIdentifier buildNameId(SAML1ProfileRequestContext requestContext) throws ProfileException {
424 if (log.isDebugEnabled()) {
425 log.debug("Building assertion NameIdentifier to relying party " + requestContext.getRelyingPartyId()
426 + " for principal " + requestContext.getPrincipalName());
428 Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
429 List<String> supportedNameFormats = getNameFormats(requestContext);
431 if (log.isDebugEnabled()) {
432 log.debug("Supported name formats: " + supportedNameFormats);
435 if (principalAttributes != null && supportedNameFormats != null) {
437 AttributeEncoder<NameIdentifier> nameIdEncoder = null;
438 for (BaseAttribute attribute : principalAttributes.values()) {
439 for (String nameFormat : supportedNameFormats) {
440 nameIdEncoder = attribute.getEncoderByCategory(nameFormat);
441 if (nameIdEncoder != null) {
442 if (log.isDebugEnabled()) {
443 log.debug("Using attribute " + attribute.getId() + " suppoting name format "
444 + nameFormat + " to create the NameIdentifier for principal "
445 + requestContext.getPrincipalName());
447 return nameIdEncoder.encode(attribute);
451 } catch (AttributeEncodingException e) {
452 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
453 "Unable to construct NameIdentifier"));
454 throw new ProfileException("Unable to encode NameIdentifier attribute", e);
458 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Unable to construct NameID"));
459 throw new ProfileException("No principal attributes support NameIdentifier construction");
463 * Gets the NameIdentifier format to use when creating NameIdentifiers for the relying party.
465 * @param requestContext current request context
467 * @return list of formats that may be used with the relying party
469 * @throws ProfileException thrown if there is a problem determing the NameIdentifier format to use
471 protected List<String> getNameFormats(SAML1ProfileRequestContext requestContext) throws ProfileException {
472 ArrayList<String> nameFormats = new ArrayList<String>();
474 RoleDescriptor assertingPartyRole = requestContext.getAssertingPartyRoleMetadata();
475 List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
477 if (nameFormats.isEmpty()) {
478 RoleDescriptor relyingPartyRole = requestContext.getRelyingPartyRoleMetadata();
479 List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
481 assertingPartySupportedFormats.retainAll(relyingPartySupportedFormats);
482 nameFormats.addAll(assertingPartySupportedFormats);
484 if (nameFormats.isEmpty()) {
485 nameFormats.add("urn:oasis:names:tc:SAML:1.0:nameid-format:unspecified");
492 * Gets the list of NameIdentifier formats supported for a given role.
494 * @param role the role to get the list of supported NameIdentifier formats
496 * @return list of supported NameIdentifier formats
498 protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
499 List<NameIDFormat> nameIDFormats = null;
501 if (role instanceof SSODescriptor) {
502 nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
503 } else if (role instanceof AuthnAuthorityDescriptor) {
504 nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
505 } else if (role instanceof PDPDescriptor) {
506 nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
507 } else if (role instanceof AttributeAuthorityDescriptor) {
508 nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
511 ArrayList<String> supportedFormats = new ArrayList<String>();
512 if (nameIDFormats != null) {
513 for (NameIDFormat format : nameIDFormats) {
514 supportedFormats.add(format.getFormat());
518 return supportedFormats;
522 * Constructs an SAML response message carrying a request error.
524 * @param requestContext current request context containing the failure status
526 * @return the constructed error response
528 protected Response buildErrorResponse(SAML1ProfileRequestContext requestContext) {
529 Response samlResponse = getResponseBuilder().buildObject();
530 samlResponse.setIssueInstant(new DateTime());
531 populateStatusResponse(requestContext, samlResponse);
533 samlResponse.setStatus(requestContext.getFailureStatus());
539 * Populates the response's id, in response to, issue instant, version, and issuer properties.
541 * @param requestContext current request context
542 * @param response the response to populate
544 protected void populateStatusResponse(SAML1ProfileRequestContext requestContext, ResponseAbstractType response) {
545 response.setID(getIdGenerator().generateIdentifier());
547 SAMLObject samlMessage = requestContext.getSamlRequest();
548 if (samlMessage != null && samlMessage instanceof RequestAbstractType) {
549 response.setInResponseTo(((RequestAbstractType) samlMessage).getID());
551 response.setVersion(SAMLVersion.VERSION_11);
555 * Build a status message, with an optional second-level failure message.
557 * @param topLevelCode top-level status code
558 * @param secondLevelCode second-level status code
559 * @param failureMessage An optional second-level failure message
561 * @return a Status object.
563 protected Status buildStatus(QName topLevelCode, QName secondLevelCode, String failureMessage) {
564 Status status = getStatusBuilder().buildObject();
566 StatusCode statusCode = getStatusCodeBuilder().buildObject();
567 statusCode.setValue(topLevelCode);
568 status.setStatusCode(statusCode);
570 if (secondLevelCode != null) {
571 StatusCode secondLevelStatusCode = getStatusCodeBuilder().buildObject();
572 secondLevelStatusCode.setValue(secondLevelCode);
573 statusCode.setStatusCode(secondLevelStatusCode);
576 if (failureMessage != null) {
577 StatusMessage msg = getStatusMessageBuilder().buildObject();
578 msg.setMessage(failureMessage);
579 status.setStatusMessage(msg);
586 * Executes a query for attributes and builds a SAML attribute statement from the results.
588 * @param requestContext current request context
589 * @param subjectConfMethod subject confirmation method
591 * @return attribute statement resulting from the query
593 * @throws ProfileException thrown if there is a problem making the query
595 protected AttributeStatement buildAttributeStatement(SAML1ProfileRequestContext requestContext,
596 String subjectConfMethod) throws ProfileException {
598 if (log.isDebugEnabled()) {
599 log.debug("Creating attribute statement in response to SAML request from relying party "
600 + requestContext.getRelyingPartyId());
603 AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
604 SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
607 if (log.isDebugEnabled()) {
608 log.debug("Resolving attributes for principal " + requestContext.getPrincipalName()
609 + " of SAML request from relying party " + requestContext.getRelyingPartyId());
611 Map<String, BaseAttribute> principalAttributes = attributeAuthority
612 .getAttributes(buildAttributeRequestContext(requestContext));
614 requestContext.setPrincipalAttributes(principalAttributes);
616 AttributeStatement statment;
617 if (requestContext.getSamlRequest() instanceof AttributeQuery) {
618 statment = attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext.getSamlRequest(),
619 principalAttributes.values());
621 statment = attributeAuthority.buildAttributeStatement(null, principalAttributes.values());
624 Subject statementSubject = buildSubject(requestContext, subjectConfMethod);
625 statment.setSubject(statementSubject);
628 } catch (AttributeRequestException e) {
629 log.error("Error resolving attributes for SAML request from relying party "
630 + requestContext.getRelyingPartyId(), e);
631 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error resolving attributes"));
632 throw new ProfileException("Error resolving attributes for SAML request from relying party "
633 + requestContext.getRelyingPartyId(), e);
638 * Resolves the principal name of the subject of the request.
640 * @param requestContext current request context
642 * @throws ProfileException thrown if the principal name can not be resolved
644 protected void resolvePrincipal(SAML1ProfileRequestContext requestContext) throws ProfileException {
645 AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
646 SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
648 if (log.isDebugEnabled()) {
649 log.debug("Resolving principal name for subject of SAML request from relying party "
650 + requestContext.getRelyingPartyId());
654 String principal = attributeAuthority.getPrincipal(buildAttributeRequestContext(requestContext));
655 requestContext.setPrincipalName(principal);
656 } catch (AttributeRequestException e) {
657 log.error("Error resolving attributes for SAML request from relying party "
658 + requestContext.getRelyingPartyId(), e);
659 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
660 "Error resolving principal"));
661 throw new ProfileException("Error resolving attributes for SAML request from relying party "
662 + requestContext.getRelyingPartyId(), e);
667 * Creates an attribute query context from the current profile request context.
669 * @param requestContext current profile request
671 * @return created query context
673 protected ShibbolethSAMLAttributeRequestContext<NameIdentifier, AttributeQuery> buildAttributeRequestContext(
674 SAML1ProfileRequestContext requestContext) {
676 ShibbolethSAMLAttributeRequestContext<NameIdentifier, AttributeQuery> queryContext;
678 if (requestContext.getSamlRequest() instanceof Request) {
679 Request samlRequest = (Request) requestContext.getSamlRequest();
680 queryContext = new ShibbolethSAMLAttributeRequestContext<NameIdentifier, AttributeQuery>(
681 getMetadataProvider(), requestContext.getRelyingPartyConfiguration(),
682 samlRequest.getAttributeQuery());
684 queryContext = new ShibbolethSAMLAttributeRequestContext<NameIdentifier, AttributeQuery>(
685 getMetadataProvider(), requestContext.getRelyingPartyConfiguration(), null);
688 queryContext.setAttributeRequester(requestContext.getAssertingPartyId());
689 queryContext.setPrincipalName(requestContext.getPrincipalName());
690 queryContext.setProfileConfiguration(requestContext.getProfileConfiguration());
691 queryContext.setRequest(requestContext.getProfileRequest());
693 Session userSession = getSessionManager().getSession(getUserSessionId(requestContext.getProfileRequest()));
694 if (userSession != null) {
695 queryContext.setUserSession(userSession);
696 ServiceInformation serviceInfo = userSession.getServicesInformation().get(
697 requestContext.getRelyingPartyId());
698 if (serviceInfo != null) {
699 String principalAuthenticationMethod = serviceInfo.getAuthenticationMethod().getAuthenticationMethod();
701 requestContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
702 queryContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
710 * Signs the given assertion if either the current profile configuration or the relying party configuration contains
711 * signing credentials.
713 * @param requestContext current request context
714 * @param assertion assertion to sign
716 * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
717 * required, if a signing credential is not configured
719 protected void signAssertion(SAML1ProfileRequestContext requestContext, Assertion assertion)
720 throws ProfileException {
721 if (log.isDebugEnabled()) {
722 log.debug("Determining if SAML assertion to relying party " + requestContext.getRelyingPartyId()
723 + " should be signed");
726 boolean signAssertion = false;
728 RoleDescriptor relyingPartyRole = requestContext.getRelyingPartyRoleMetadata();
729 AbstractSAML1ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
731 if (relyingPartyRole instanceof SPSSODescriptor) {
732 SPSSODescriptor ssoDescriptor = (SPSSODescriptor) relyingPartyRole;
733 if (ssoDescriptor.getWantAssertionsSigned() != null) {
734 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
735 if (log.isDebugEnabled()) {
736 log.debug("Entity metadata for relying party " + requestContext.getRelyingPartyId()
737 + " indicates to sign assertions: " + signAssertion);
740 } else if (profileConfig.getSignAssertions()) {
741 signAssertion = true;
742 log.debug("IdP relying party configuration "
743 + requestContext.getRelyingPartyConfiguration().getRelyingPartyId()
744 + " indicates to sign assertions: " + signAssertion);
747 if (!signAssertion) {
751 if (log.isDebugEnabled()) {
752 log.debug("Determining signing credntial for assertion to relying party "
753 + requestContext.getRelyingPartyId());
755 Credential signatureCredential = profileConfig.getSigningCredential();
756 if (signatureCredential == null) {
757 signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
760 if (signatureCredential == null) {
761 throw new ProfileException("No signing credential is specified for relying party configuration "
762 + requestContext.getRelyingPartyConfiguration().getProviderId()
763 + " or it's SAML2 attribute query profile configuration");
766 if (log.isDebugEnabled()) {
767 log.debug("Signing assertion to relying party " + requestContext.getRelyingPartyId());
769 SAMLObjectContentReference contentRef = new SAMLObjectContentReference(assertion);
770 Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
771 signature.getContentReferences().add(contentRef);
772 assertion.setSignature(signature);
774 Signer.signObject(signature);
778 * Writes an aduit log entry indicating the successful response to the attribute request.
780 * @param context current request context
782 protected void writeAuditLogEntry(SAML1ProfileRequestContext context) {
783 AuditLogEntry auditLogEntry = new AuditLogEntry();
784 auditLogEntry.setMessageProfile(getProfileId());
785 auditLogEntry.setPrincipalAuthenticationMethod(context.getPrincipalAuthenticationMethod());
786 auditLogEntry.setPrincipalName(context.getPrincipalName());
787 auditLogEntry.setAssertingPartyId(context.getAssertingPartyId());
788 auditLogEntry.setRelyingPartyId(context.getRelyingPartyId());
789 auditLogEntry.setRequestBinding(context.getMessageDecoder().getBindingURI());
790 auditLogEntry.setRequestId(null);
791 auditLogEntry.setResponseBinding(context.getMessageEncoder().getBindingURI());
792 auditLogEntry.setResponseId(context.getSamlResponse().getID());
793 getAduitLog().log(Level.CRITICAL, auditLogEntry);
797 * Contextual object used to accumlate information as profile requests are being processed.
799 * @param <RequestType> type of SAML 1 request
800 * @param <ResponseType> type of SAML 1 response
801 * @param <ProfileConfigurationType> configuration type for this profile
803 protected class SAML1ProfileRequestContext<RequestType extends RequestAbstractType, ResponseType extends ResponseAbstractType, ProfileConfigurationType extends AbstractSAML1ProfileConfiguration>
804 extends SAMLProfileRequestContext {
806 /** SAML request message. */
807 private RequestType samlRequest;
809 /** SAML response message. */
810 private ResponseType samlResponse;
812 /** Request profile configuration. */
813 private ProfileConfigurationType profileConfiguration;
815 /** The NameIdentifier of the subject of this request. */
816 private NameIdentifier subjectNameIdentifier;
818 /** The request failure status. */
819 private Status failureStatus;
824 * @param request current profile request
825 * @param response current profile response
827 public SAML1ProfileRequestContext(ProfileRequest<ServletRequest> request,
828 ProfileResponse<ServletResponse> response) {
829 super(request, response);
833 * Gets the NameIdentifier of the subject of this request.
835 * @return NameIdentifier of the subject of this request
837 public NameIdentifier getSubjectNameID() {
838 return subjectNameIdentifier;
842 * Sets the NameIdentifier of the subject of this request.
844 * @param id NameIdentifier of the subject of this request
846 public void setSubjectNameID(NameIdentifier id) {
847 subjectNameIdentifier = id;
851 * Gets the profile configuration for this request.
853 * @return profile configuration for this request
855 public ProfileConfigurationType getProfileConfiguration() {
856 return profileConfiguration;
860 * Sets the profile configuration for this request.
862 * @param configuration profile configuration for this request
864 public void setProfileConfiguration(ProfileConfigurationType configuration) {
865 profileConfiguration = configuration;
869 * Gets the SAML request message.
871 * @return SAML request message
873 public RequestType getSamlRequest() {
878 * Sets the SAML request message.
880 * @param request SAML request message
882 public void setSamlRequest(RequestType request) {
883 samlRequest = request;
887 * Gets the SAML response message.
889 * @return SAML response message
891 public ResponseType getSamlResponse() {
896 * Sets the SAML response message.
898 * @param response SAML response message
900 public void setSamlResponse(ResponseType response) {
901 samlResponse = response;
905 * Gets the status reflecting a request failure.
907 * @return status reflecting a request failure
909 public Status getFailureStatus() {
910 return failureStatus;
914 * Sets the status reflecting a request failure.
916 * @param status status reflecting a request failure
918 public void setFailureStatus(Status status) {
919 failureStatus = status;