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;
27 import org.apache.log4j.Logger;
28 import org.joda.time.DateTime;
29 import org.opensaml.common.SAMLObject;
30 import org.opensaml.common.SAMLObjectBuilder;
31 import org.opensaml.common.SAMLVersion;
32 import org.opensaml.common.impl.SAMLObjectContentReference;
33 import org.opensaml.common.xml.SAMLConstants;
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.Query;
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.saml2.metadata.provider.MetadataProviderException;
61 import org.opensaml.xml.XMLObjectBuilder;
62 import org.opensaml.xml.security.credential.Credential;
63 import org.opensaml.xml.signature.Signature;
64 import org.opensaml.xml.signature.Signer;
65 import org.opensaml.xml.util.DatatypeHelper;
67 import edu.internet2.middleware.shibboleth.common.attribute.AttributeRequestException;
68 import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
69 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncoder;
70 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncodingException;
71 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML1AttributeAuthority;
72 import edu.internet2.middleware.shibboleth.common.attribute.provider.ShibbolethSAMLAttributeRequestContext;
73 import edu.internet2.middleware.shibboleth.common.log.AuditLogEntry;
74 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
75 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
76 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
77 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.AbstractSAML1ProfileConfiguration;
78 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
79 import edu.internet2.middleware.shibboleth.idp.session.ServiceInformation;
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 = Logger.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 NameIdentifier objects. */
107 private SAMLObjectBuilder<NameIdentifier> nameIdBuilder;
109 /** Builder of SubjectConfirmation objects. */
110 private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
112 /** Builder of ConfirmationMethod objects. */
113 private SAMLObjectBuilder<ConfirmationMethod> confirmationMethodBuilder;
115 /** Builder of Subject objects. */
116 private SAMLObjectBuilder<Subject> subjectBuilder;
118 /** Builder for Status objects. */
119 private SAMLObjectBuilder<Status> statusBuilder;
121 /** Builder for StatusCode objects. */
122 private SAMLObjectBuilder<StatusCode> statusCodeBuilder;
124 /** Builder for StatusMessage objects. */
125 private SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
127 /** For building signature. */
128 private XMLObjectBuilder<Signature> signatureBuilder;
131 * Default constructor.
133 @SuppressWarnings("unchecked")
134 public AbstractSAML1ProfileHandler() {
136 responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
137 assertionBuilder = (SAMLObjectBuilder<Assertion>) getBuilderFactory()
138 .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
139 conditionsBuilder = (SAMLObjectBuilder<Conditions>) getBuilderFactory().getBuilder(
140 Conditions.DEFAULT_ELEMENT_NAME);
141 audienceRestrictionConditionBuilder = (SAMLObjectBuilder<AudienceRestrictionCondition>) getBuilderFactory()
142 .getBuilder(AudienceRestrictionCondition.DEFAULT_ELEMENT_NAME);
143 audienceBuilder = (SAMLObjectBuilder<Audience>) getBuilderFactory().getBuilder(Audience.DEFAULT_ELEMENT_NAME);
144 nameIdBuilder = (SAMLObjectBuilder<NameIdentifier>) getBuilderFactory().getBuilder(
145 NameIdentifier.DEFAULT_ELEMENT_NAME);
146 subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) getBuilderFactory().getBuilder(
147 SubjectConfirmation.DEFAULT_ELEMENT_NAME);
148 confirmationMethodBuilder = (SAMLObjectBuilder<ConfirmationMethod>) getBuilderFactory().getBuilder(
149 ConfirmationMethod.DEFAULT_ELEMENT_NAME);
150 subjectBuilder = (SAMLObjectBuilder<Subject>) getBuilderFactory().getBuilder(Subject.DEFAULT_ELEMENT_NAME);
151 statusBuilder = (SAMLObjectBuilder<Status>) getBuilderFactory().getBuilder(Status.DEFAULT_ELEMENT_NAME);
152 statusCodeBuilder = (SAMLObjectBuilder<StatusCode>) getBuilderFactory().getBuilder(
153 StatusCode.DEFAULT_ELEMENT_NAME);
154 statusMessageBuilder = (SAMLObjectBuilder<StatusMessage>) getBuilderFactory().getBuilder(
155 StatusMessage.DEFAULT_ELEMENT_NAME);
156 signatureBuilder = (XMLObjectBuilder<Signature>) getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
160 * Convenience method for getting the SAML 1 Response builder.
162 * @return SAML 1 Response builder
164 public SAMLObjectBuilder<Response> getResponseBuilder() {
165 return responseBuilder;
169 * Convenience method for getting the SAML 1 Assertion builder.
171 * @return SAML 1 Assertion builder
173 public SAMLObjectBuilder<Assertion> getAssertionBuilder() {
174 return assertionBuilder;
178 * Convenience method for getting the SAML 1 Conditions builder.
180 * @return SAML 1 Conditions builder
182 public SAMLObjectBuilder<Conditions> getConditionsBuilder() {
183 return conditionsBuilder;
187 * Convenience method for getting the SAML 1 AudienceRestrictionCondition builder.
189 * @return SAML 1 AudienceRestrictionCondition builder
191 public SAMLObjectBuilder<AudienceRestrictionCondition> getAudienceRestrictionConditionBuilder() {
192 return audienceRestrictionConditionBuilder;
196 * Convenience method for getting the SAML 1 Audience builder.
198 * @return SAML 1 Audience builder
200 public SAMLObjectBuilder<Audience> getAudienceBuilder() {
201 return audienceBuilder;
205 * Convenience method for getting the SAML 1 NameIdentifier builder.
207 * @return SAML 1 NameIdentifier builder
209 public SAMLObjectBuilder<NameIdentifier> getNameIdentifierBuilder() {
210 return nameIdBuilder;
214 * Convenience method for getting the SAML 1 SubjectConfirmation builder.
216 * @return SAML 1 SubjectConfirmation builder
218 public SAMLObjectBuilder<SubjectConfirmation> getSubjectConfirmationBuilder() {
219 return subjectConfirmationBuilder;
223 * Convenience method for getting the SAML 1 ConfirmationMethod builder.
225 * @return SAML 1 ConfirmationMethod builder
227 public SAMLObjectBuilder<ConfirmationMethod> getConfirmationMethodBuilder() {
228 return confirmationMethodBuilder;
232 * Convenience method for getting the SAML 1 Subject builder.
234 * @return SAML 1 Subject builder
236 public SAMLObjectBuilder<Subject> getSubjectBuilder() {
237 return subjectBuilder;
241 * Convenience method for getting the SAML 1 Status builder.
243 * @return SAML 1 Status builder
245 public SAMLObjectBuilder<Status> getStatusBuilder() {
246 return statusBuilder;
250 * Convenience method for getting the SAML 1 StatusCode builder.
252 * @return SAML 2 StatusCode builder
254 public SAMLObjectBuilder<StatusCode> getStatusCodeBuilder() {
255 return statusCodeBuilder;
259 * Convenience method for getting the SAML 1 StatusMessage builder.
261 * @return SAML StatusMessage builder
263 public SAMLObjectBuilder<StatusMessage> getStatusMessageBuilder() {
264 return statusMessageBuilder;
268 * Checks that the SAML major version for a request is 1.
270 * @param requestContext current request context containing the SAML message
272 * @throws ProfileException thrown if the major version of the SAML request is not 1
274 protected void checkSamlVersion(SAML1ProfileRequestContext requestContext) throws ProfileException {
275 SAMLObject samlObject = requestContext.getSamlRequest();
277 if (samlObject instanceof RequestAbstractType) {
278 RequestAbstractType request = (RequestAbstractType) samlObject;
279 if (request.getMajorVersion() < 1) {
280 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER, StatusCode.REQUEST_VERSION_TOO_LOW,
282 throw new ProfileException("SAML request major version too low");
283 } else if (request.getMajorVersion() > 1) {
284 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER, StatusCode.REQUEST_VERSION_TOO_HIGH,
286 throw new ProfileException("SAML request major version too low");
292 * Builds a response to the attribute query within the request context.
294 * @param requestContext current request context
295 * @param statements the statements to include in the response
297 * @return the built response
299 * @throws ProfileException thrown if there is a problem creating the SAML response
301 protected Response buildResponse(SAML1ProfileRequestContext requestContext, List<Statement> statements)
302 throws ProfileException {
304 DateTime issueInstant = new DateTime();
306 // create the assertion and add the attribute statement
307 Assertion assertion = buildAssertion(requestContext, issueInstant);
308 if (statements != null) {
309 assertion.getStatements().addAll(statements);
312 // create the SAML response and add the assertion
313 Response samlResponse = getResponseBuilder().buildObject();
314 samlResponse.setIssueInstant(issueInstant);
315 populateStatusResponse(requestContext, samlResponse);
317 samlResponse.getAssertions().add(assertion);
319 // sign the assertion if it should be signed
320 signAssertion(requestContext, assertion);
322 Status status = buildStatus(StatusCode.SUCCESS, null, null);
323 samlResponse.setStatus(status);
329 * Builds a basic assertion with its id, issue instant, SAML version, issuer, subject, and conditions populated.
331 * @param requestContext current request context
332 * @param issueInstant time to use as assertion issue instant
334 * @return the built assertion
336 protected Assertion buildAssertion(SAML1ProfileRequestContext requestContext, DateTime issueInstant) {
337 Assertion assertion = getAssertionBuilder().buildObject();
338 assertion.setID(getIdGenerator().generateIdentifier());
339 assertion.setIssueInstant(issueInstant);
340 assertion.setVersion(SAMLVersion.VERSION_11);
341 assertion.setIssuer(requestContext.getAssertingPartyId());
343 Conditions conditions = buildConditions(requestContext, issueInstant);
344 assertion.setConditions(conditions);
350 * Builds a SAML assertion condition set. The following fields are set; not before, not on or after, audience
351 * restrictions, and proxy restrictions.
353 * @param requestContext current request context
354 * @param issueInstant timestamp the assertion was created
356 * @return constructed conditions
358 protected Conditions buildConditions(SAML1ProfileRequestContext requestContext, DateTime issueInstant) {
359 AbstractSAML1ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
361 Conditions conditions = getConditionsBuilder().buildObject();
362 conditions.setNotBefore(issueInstant);
363 conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
365 Collection<String> audiences;
367 // add audience restrictions
368 audiences = profileConfig.getAssertionAudiences();
369 if (audiences != null && audiences.size() > 0) {
370 AudienceRestrictionCondition audienceRestriction = getAudienceRestrictionConditionBuilder().buildObject();
371 for (String audienceUri : audiences) {
372 Audience audience = getAudienceBuilder().buildObject();
373 audience.setUri(audienceUri);
374 audienceRestriction.getAudiences().add(audience);
376 conditions.getAudienceRestrictionConditions().add(audienceRestriction);
383 * Builds the SAML subject for the user for the service provider.
385 * @param requestContext current request context
386 * @param confirmationMethod subject confirmation method used for the subject
388 * @return SAML subject for the user for the service provider
390 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
391 * name ID attribute or because there are no supported name formats
393 protected Subject buildSubject(SAML1ProfileRequestContext requestContext, String confirmationMethod)
394 throws ProfileException {
395 NameIdentifier nameID = buildNameId(requestContext);
396 requestContext.setSubjectNameID(nameID);
398 ConfirmationMethod method = getConfirmationMethodBuilder().buildObject();
399 method.setConfirmationMethod(confirmationMethod);
401 SubjectConfirmation subjectConfirmation = getSubjectConfirmationBuilder().buildObject();
402 subjectConfirmation.getConfirmationMethods().add(method);
404 Subject subject = getSubjectBuilder().buildObject();
405 subject.setNameIdentifier(nameID);
406 subject.setSubjectConfirmation(subjectConfirmation);
412 * Builds a NameIdentifier appropriate for this request. NameIdentifier are built by inspecting the SAML request and
413 * metadata, picking a name format that was requested by the relying party or is mutually supported by both the
414 * relying party and asserting party as described in their metadata entries. Once a set of supported name formats is
415 * determined the principals attributes are inspected for an attribtue supported an attribute encoder whose category
416 * is one of the supported name formats.
418 * @param requestContext current request context
420 * @return the NameIdentifier appropriate for this request
422 * @throws ProfileException thrown if a NameIdentifier can not be created either because there was a problem
423 * encoding the name ID attribute or because there are no supported name formats
425 protected NameIdentifier buildNameId(SAML1ProfileRequestContext requestContext) throws ProfileException {
426 if (log.isDebugEnabled()) {
427 log.debug("Building assertion NameIdentifier to relying party " + requestContext.getRelyingPartyId()
428 + " for principal " + requestContext.getPrincipalName());
430 Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
431 List<String> supportedNameFormats = getNameFormats(requestContext);
433 if (log.isDebugEnabled()) {
434 log.debug("Supported name formats: " + supportedNameFormats);
437 if (principalAttributes != null && supportedNameFormats != null) {
439 AttributeEncoder<NameIdentifier> nameIdEncoder = null;
440 for (BaseAttribute attribute : principalAttributes.values()) {
441 for (String nameFormat : supportedNameFormats) {
442 nameIdEncoder = attribute.getEncoderByCategory(nameFormat);
443 if (nameIdEncoder != null) {
444 if (log.isDebugEnabled()) {
445 log.debug("Using attribute " + attribute.getId() + " suppoting name format "
446 + nameFormat + " to create the NameIdentifier for principal "
447 + requestContext.getPrincipalName());
449 return nameIdEncoder.encode(attribute);
453 } catch (AttributeEncodingException e) {
454 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
455 "Unable to construct NameIdentifier"));
456 throw new ProfileException("Unable to encode NameIdentifier attribute", e);
460 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Unable to construct NameID"));
461 throw new ProfileException("No principal attributes support NameIdentifier construction");
465 * Gets the NameIdentifier format to use when creating NameIdentifiers for the relying party.
467 * @param requestContext current request context
469 * @return list of formats that may be used with the relying party
471 * @throws ProfileException thrown if there is a problem determing the NameIdentifier format to use
473 protected List<String> getNameFormats(SAML1ProfileRequestContext requestContext) throws ProfileException {
474 ArrayList<String> nameFormats = new ArrayList<String>();
477 RoleDescriptor assertingPartyRole = getMetadataProvider().getRole(requestContext.getAssertingPartyId(),
478 requestContext.getAssertingPartyRole(), SAMLConstants.SAML1P_NS);
479 List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
481 if (nameFormats.isEmpty()) {
482 RoleDescriptor relyingPartyRole = getMetadataProvider().getRole(requestContext.getRelyingPartyId(),
483 requestContext.getRelyingPartyRole(), SAMLConstants.SAML1P_NS);
484 List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
486 assertingPartySupportedFormats.retainAll(relyingPartySupportedFormats);
487 nameFormats.addAll(assertingPartySupportedFormats);
489 if (nameFormats.isEmpty()) {
490 nameFormats.add("urn:oasis:names:tc:SAML:1.0:nameid-format:unspecified");
495 } catch (MetadataProviderException e) {
496 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Unable to lookup metadata"));
497 throw new ProfileException("Unable to determine lookup entity metadata", e);
502 * Gets the list of NameIdentifier formats supported for a given role.
504 * @param role the role to get the list of supported NameIdentifier formats
506 * @return list of supported NameIdentifier formats
508 protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
509 List<NameIDFormat> nameIDFormats = null;
511 if (role instanceof SSODescriptor) {
512 nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
513 } else if (role instanceof AuthnAuthorityDescriptor) {
514 nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
515 } else if (role instanceof PDPDescriptor) {
516 nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
517 } else if (role instanceof AttributeAuthorityDescriptor) {
518 nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
521 ArrayList<String> supportedFormats = new ArrayList<String>();
522 if (nameIDFormats != null) {
523 for (NameIDFormat format : nameIDFormats) {
524 supportedFormats.add(format.getFormat());
528 return supportedFormats;
532 * Constructs an SAML response message carrying a request error.
534 * @param requestContext current request context containing the failure status
536 * @return the constructed error response
538 protected Response buildErrorResponse(SAML1ProfileRequestContext requestContext) {
539 Response samlResponse = getResponseBuilder().buildObject();
540 samlResponse.setIssueInstant(new DateTime());
541 populateStatusResponse(requestContext, samlResponse);
543 samlResponse.setStatus(requestContext.getFailureStatus());
549 * Populates the response's id, in response to, issue instant, version, and issuer properties.
551 * @param requestContext current request context
552 * @param response the response to populate
554 protected void populateStatusResponse(SAML1ProfileRequestContext requestContext, ResponseAbstractType response) {
555 response.setID(getIdGenerator().generateIdentifier());
557 SAMLObject samlMessage = requestContext.getSamlRequest();
558 if (samlMessage != null && samlMessage instanceof RequestAbstractType) {
559 response.setInResponseTo(((RequestAbstractType) samlMessage).getID());
561 response.setVersion(SAMLVersion.VERSION_11);
565 * Build a status message, with an optional second-level failure message.
567 * @param topLevelCode top-level status code
568 * @param secondLevelCode second-level status code
569 * @param failureMessage An optional second-level failure message
571 * @return a Status object.
573 protected Status buildStatus(String topLevelCode, String secondLevelCode, String failureMessage) {
574 Status status = getStatusBuilder().buildObject();
576 StatusCode statusCode = getStatusCodeBuilder().buildObject();
577 statusCode.setValue(DatatypeHelper.safeTrimOrNullString(topLevelCode));
578 status.setStatusCode(statusCode);
580 if (secondLevelCode != null) {
581 StatusCode secondLevelStatusCode = getStatusCodeBuilder().buildObject();
582 secondLevelStatusCode.setValue(DatatypeHelper.safeTrimOrNullString(secondLevelCode));
583 statusCode.setStatusCode(secondLevelStatusCode);
586 if (failureMessage != null) {
587 StatusMessage msg = getStatusMessageBuilder().buildObject();
588 msg.setMessage(failureMessage);
589 status.setStatusMessage(msg);
596 * Executes a query for attributes and builds a SAML attribute statement from the results.
598 * @param requestContext current request context
599 * @param subjectConfMethod subject confirmation method
601 * @return attribute statement resulting from the query
603 * @throws ProfileException thrown if there is a problem making the query
605 protected AttributeStatement buildAttributeStatement(SAML1ProfileRequestContext requestContext,
606 String subjectConfMethod) throws ProfileException {
608 if (log.isDebugEnabled()) {
609 log.debug("Creating attribute statement in response to SAML request from relying party "
610 + requestContext.getRelyingPartyId());
613 AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
614 SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
617 if (log.isDebugEnabled()) {
618 log.debug("Resolving attributes for principal " + requestContext.getPrincipalName()
619 + " of SAML request from relying party " + requestContext.getRelyingPartyId());
621 Map<String, BaseAttribute> principalAttributes = attributeAuthority
622 .getAttributes(buildAttributeRequestContext(requestContext));
624 requestContext.setPrincipalAttributes(principalAttributes);
626 AttributeStatement statment;
627 if (requestContext.getSamlRequest() instanceof AttributeQuery) {
628 statment = attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext.getSamlRequest(),
629 principalAttributes.values());
631 statment = attributeAuthority.buildAttributeStatement(null, principalAttributes.values());
634 Subject statementSubject = buildSubject(requestContext, subjectConfMethod);
635 statment.setSubject(statementSubject);
638 } catch (AttributeRequestException e) {
639 log.error("Error resolving attributes for SAML request from relying party "
640 + requestContext.getRelyingPartyId(), e);
641 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error resolving attributes"));
642 throw new ProfileException("Error resolving attributes for SAML request from relying party "
643 + requestContext.getRelyingPartyId(), e);
648 * Resolves the principal name of the subject of the request.
650 * @param requestContext current request context
652 * @throws ProfileException thrown if the principal name can not be resolved
654 protected void resolvePrincipal(SAML1ProfileRequestContext requestContext) throws ProfileException {
655 AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
656 SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
658 if (log.isDebugEnabled()) {
659 log.debug("Resolving principal name for subject of SAML request from relying party "
660 + requestContext.getRelyingPartyId());
664 String principal = attributeAuthority.getPrincipal(buildAttributeRequestContext(requestContext));
665 requestContext.setPrincipalName(principal);
666 } catch (AttributeRequestException e) {
667 log.error("Error resolving attributes for SAML request from relying party "
668 + requestContext.getRelyingPartyId(), e);
669 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
670 "Error resolving principal"));
671 throw new ProfileException("Error resolving attributes for SAML request from relying party "
672 + requestContext.getRelyingPartyId(), e);
677 * Creates an attribute query context from the current profile request context.
679 * @param requestContext current profile request
681 * @return created query context
683 protected ShibbolethSAMLAttributeRequestContext<NameIdentifier, AttributeQuery> buildAttributeRequestContext(
684 SAML1ProfileRequestContext requestContext) {
686 ShibbolethSAMLAttributeRequestContext<NameIdentifier, AttributeQuery> queryContext;
688 if (requestContext.getSamlRequest() instanceof AttributeQuery) {
689 queryContext = new ShibbolethSAMLAttributeRequestContext<NameIdentifier, AttributeQuery>(
690 getMetadataProvider(), requestContext.getRelyingPartyConfiguration(),
691 (AttributeQuery) requestContext.getSamlRequest());
693 queryContext = new ShibbolethSAMLAttributeRequestContext<NameIdentifier, AttributeQuery>(
694 getMetadataProvider(), requestContext.getRelyingPartyConfiguration());
697 queryContext.setAttributeRequester(requestContext.getAssertingPartyId());
698 queryContext.setPrincipalName(requestContext.getPrincipalName());
699 queryContext.setProfileConfiguration(requestContext.getProfileConfiguration());
700 queryContext.setRequest(requestContext.getProfileRequest());
702 Session userSession = getSessionManager().getSession(getUserSessionId(requestContext.getProfileRequest()));
703 if (userSession != null) {
704 queryContext.setUserSession(userSession);
705 ServiceInformation serviceInfo = userSession.getServiceInformation(requestContext.getRelyingPartyId());
706 if (serviceInfo != null) {
707 String principalAuthenticationMethod = serviceInfo.getAuthenticationMethod().getAuthenticationMethod();
709 requestContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
710 queryContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
718 * Signs the given assertion if either the current profile configuration or the relying party configuration contains
719 * signing credentials.
721 * @param requestContext current request context
722 * @param assertion assertion to sign
724 * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
725 * required, if a signing credential is not configured
727 protected void signAssertion(SAML1ProfileRequestContext requestContext, Assertion assertion)
728 throws ProfileException {
729 if (log.isDebugEnabled()) {
730 log.debug("Determining if SAML assertion to relying party " + requestContext.getRelyingPartyId()
731 + " should be signed");
734 boolean signAssertion = false;
736 RoleDescriptor relyingPartyRole;
738 relyingPartyRole = getMetadataProvider().getRole(requestContext.getRelyingPartyId(),
739 requestContext.getRelyingPartyRole(), SAMLConstants.SAML20P_NS);
740 } catch (MetadataProviderException e) {
741 throw new ProfileException("Unable to lookup entity metadata for relying party "
742 + requestContext.getRelyingPartyId());
744 AbstractSAML1ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
746 if (relyingPartyRole instanceof SPSSODescriptor) {
747 SPSSODescriptor ssoDescriptor = (SPSSODescriptor) relyingPartyRole;
748 if (ssoDescriptor.getWantAssertionsSigned() != null) {
749 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
750 if (log.isDebugEnabled()) {
751 log.debug("Entity metadata for relying party " + requestContext.getRelyingPartyId()
752 + " indicates to sign assertions: " + signAssertion);
755 } else if (profileConfig.getSignAssertions()) {
756 signAssertion = true;
757 log.debug("IdP relying party configuration "
758 + requestContext.getRelyingPartyConfiguration().getRelyingPartyId()
759 + " indicates to sign assertions: " + signAssertion);
762 if (!signAssertion) {
766 if (log.isDebugEnabled()) {
767 log.debug("Determining signing credntial for assertion to relying party "
768 + requestContext.getRelyingPartyId());
770 Credential signatureCredential = profileConfig.getSigningCredential();
771 if (signatureCredential == null) {
772 signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
775 if (signatureCredential == null) {
776 throw new ProfileException("No signing credential is specified for relying party configuration "
777 + requestContext.getRelyingPartyConfiguration().getProviderId()
778 + " or it's SAML2 attribute query profile configuration");
781 if (log.isDebugEnabled()) {
782 log.debug("Signing assertion to relying party " + requestContext.getRelyingPartyId());
784 SAMLObjectContentReference contentRef = new SAMLObjectContentReference(assertion);
785 Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
786 signature.getContentReferences().add(contentRef);
787 assertion.setSignature(signature);
789 Signer.signObject(signature);
793 * Writes an aduit log entry indicating the successful response to the attribute request.
795 * @param context current request context
797 protected void writeAuditLogEntry(SAML1ProfileRequestContext context) {
798 AuditLogEntry auditLogEntry = new AuditLogEntry();
799 auditLogEntry.setMessageProfile(getProfileId());
800 auditLogEntry.setPrincipalAuthenticationMethod(context.getPrincipalAuthenticationMethod());
801 auditLogEntry.setPrincipalName(context.getPrincipalName());
802 auditLogEntry.setAssertingPartyId(context.getAssertingPartyId());
803 auditLogEntry.setRelyingPartyId(context.getRelyingPartyId());
804 auditLogEntry.setRequestBinding(context.getMessageDecoder().getBindingURI());
805 auditLogEntry.setRequestId(null);
806 auditLogEntry.setResponseBinding(context.getMessageEncoder().getBindingURI());
807 auditLogEntry.setResponseId(context.getSamlResponse().getID());
808 getAduitLog().log(Level.CRITICAL, auditLogEntry);
812 * Contextual object used to accumlate information as profile requests are being processed.
814 * @param <RequestType> type of SAML 1 request
815 * @param <ResponseType> type of SAML 1 response
816 * @param <ProfileConfigurationType> configuration type for this profile
818 protected class SAML1ProfileRequestContext<RequestType extends SAMLObject, ResponseType extends ResponseAbstractType, ProfileConfigurationType extends AbstractSAML1ProfileConfiguration>
819 extends SAMLProfileRequestContext {
821 /** SAML request message. */
822 private RequestType samlRequest;
824 /** SAML response message. */
825 private ResponseType samlResponse;
827 /** Request profile configuration. */
828 private ProfileConfigurationType profileConfiguration;
830 /** The NameIdentifier of the subject of this request. */
831 private NameIdentifier subjectNameIdentifier;
833 /** The request failure status. */
834 private Status failureStatus;
839 * @param request current profile request
840 * @param response current profile response
842 public SAML1ProfileRequestContext(ProfileRequest<ServletRequest> request,
843 ProfileResponse<ServletResponse> response) {
844 super(request, response);
848 * Gets the NameIdentifier of the subject of this request.
850 * @return NameIdentifier of the subject of this request
852 public NameIdentifier getSubjectNameID() {
853 return subjectNameIdentifier;
857 * Sets the NameIdentifier of the subject of this request.
859 * @param id NameIdentifier of the subject of this request
861 public void setSubjectNameID(NameIdentifier id) {
862 subjectNameIdentifier = id;
866 * Gets the profile configuration for this request.
868 * @return profile configuration for this request
870 public ProfileConfigurationType getProfileConfiguration() {
871 return profileConfiguration;
875 * Sets the profile configuration for this request.
877 * @param configuration profile configuration for this request
879 public void setProfileConfiguration(ProfileConfigurationType configuration) {
880 profileConfiguration = configuration;
884 * Gets the SAML request message.
886 * @return SAML request message
888 public RequestType getSamlRequest() {
893 * Sets the SAML request message.
895 * @param request SAML request message
897 public void setSamlRequest(RequestType request) {
898 samlRequest = request;
902 * Gets the SAML response message.
904 * @return SAML response message
906 public ResponseType getSamlResponse() {
911 * Sets the SAML response message.
913 * @param response SAML response message
915 public void setSamlResponse(ResponseType response) {
916 samlResponse = response;
920 * Gets the status reflecting a request failure.
922 * @return status reflecting a request failure
924 public Status getFailureStatus() {
925 return failureStatus;
929 * Sets the status reflecting a request failure.
931 * @param status status reflecting a request failure
933 public void setFailureStatus(Status status) {
934 failureStatus = status;