Better example resolver and filter files
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml1 / AbstractSAML1ProfileHandler.java
1 /*
2  * Copyright [2007] [University Corporation for Advanced Internet Development, Inc.]
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package edu.internet2.middleware.shibboleth.idp.profile.saml1;
18
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.List;
22 import java.util.Map;
23
24 import javax.xml.namespace.QName;
25
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.saml1.core.Assertion;
32 import org.opensaml.saml1.core.AttributeQuery;
33 import org.opensaml.saml1.core.AttributeStatement;
34 import org.opensaml.saml1.core.Audience;
35 import org.opensaml.saml1.core.AudienceRestrictionCondition;
36 import org.opensaml.saml1.core.Conditions;
37 import org.opensaml.saml1.core.ConfirmationMethod;
38 import org.opensaml.saml1.core.NameIdentifier;
39 import org.opensaml.saml1.core.RequestAbstractType;
40 import org.opensaml.saml1.core.Response;
41 import org.opensaml.saml1.core.ResponseAbstractType;
42 import org.opensaml.saml1.core.Statement;
43 import org.opensaml.saml1.core.Status;
44 import org.opensaml.saml1.core.StatusCode;
45 import org.opensaml.saml1.core.StatusMessage;
46 import org.opensaml.saml1.core.Subject;
47 import org.opensaml.saml1.core.SubjectConfirmation;
48 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
49 import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor;
50 import org.opensaml.saml2.metadata.NameIDFormat;
51 import org.opensaml.saml2.metadata.PDPDescriptor;
52 import org.opensaml.saml2.metadata.RoleDescriptor;
53 import org.opensaml.saml2.metadata.SPSSODescriptor;
54 import org.opensaml.saml2.metadata.SSODescriptor;
55 import org.opensaml.xml.XMLObjectBuilder;
56 import org.opensaml.xml.io.Marshaller;
57 import org.opensaml.xml.io.MarshallingException;
58 import org.opensaml.xml.security.SecurityException;
59 import org.opensaml.xml.security.SecurityHelper;
60 import org.opensaml.xml.security.credential.Credential;
61 import org.opensaml.xml.signature.Signature;
62 import org.opensaml.xml.signature.Signer;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 import edu.internet2.middleware.shibboleth.common.attribute.AttributeRequestException;
67 import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
68 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncoder;
69 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncodingException;
70 import edu.internet2.middleware.shibboleth.common.attribute.encoding.SAML1NameIdentifierEncoder;
71 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML1AttributeAuthority;
72 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
73 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.AbstractSAML1ProfileConfiguration;
74 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
75
76 /** Common implementation details for profile handlers. */
77 public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHandler {
78
79     /** SAML Version for this profile handler. */
80     public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_11;
81
82     /** Class logger. */
83     private static Logger log = LoggerFactory.getLogger(AbstractSAML1ProfileHandler.class);
84
85     /** Builder of Response objects. */
86     private SAMLObjectBuilder<Response> responseBuilder;
87
88     /** Builder of Assertion objects. */
89     private SAMLObjectBuilder<Assertion> assertionBuilder;
90
91     /** Builder of Conditions objects. */
92     private SAMLObjectBuilder<Conditions> conditionsBuilder;
93
94     /** Builder of AudienceRestrictionCondition objects. */
95     private SAMLObjectBuilder<AudienceRestrictionCondition> audienceRestrictionConditionBuilder;
96
97     /** Builder of AudienceRestrictionCondition objects. */
98     private SAMLObjectBuilder<Audience> audienceBuilder;
99
100     /** Builder of SubjectConfirmation objects. */
101     private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
102
103     /** Builder of ConfirmationMethod objects. */
104     private SAMLObjectBuilder<ConfirmationMethod> confirmationMethodBuilder;
105
106     /** Builder of Subject objects. */
107     private SAMLObjectBuilder<Subject> subjectBuilder;
108
109     /** Builder for Status objects. */
110     private SAMLObjectBuilder<Status> statusBuilder;
111
112     /** Builder for StatusCode objects. */
113     private SAMLObjectBuilder<StatusCode> statusCodeBuilder;
114
115     /** Builder for StatusMessage objects. */
116     private SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
117
118     /** For building signature. */
119     private XMLObjectBuilder<Signature> signatureBuilder;
120
121     /**
122      * Default constructor.
123      */
124     @SuppressWarnings("unchecked")
125     public AbstractSAML1ProfileHandler() {
126         super();
127         responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
128         assertionBuilder = (SAMLObjectBuilder<Assertion>) getBuilderFactory()
129                 .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
130         conditionsBuilder = (SAMLObjectBuilder<Conditions>) getBuilderFactory().getBuilder(
131                 Conditions.DEFAULT_ELEMENT_NAME);
132         audienceRestrictionConditionBuilder = (SAMLObjectBuilder<AudienceRestrictionCondition>) getBuilderFactory()
133                 .getBuilder(AudienceRestrictionCondition.DEFAULT_ELEMENT_NAME);
134         audienceBuilder = (SAMLObjectBuilder<Audience>) getBuilderFactory().getBuilder(Audience.DEFAULT_ELEMENT_NAME);
135         subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) getBuilderFactory().getBuilder(
136                 SubjectConfirmation.DEFAULT_ELEMENT_NAME);
137         confirmationMethodBuilder = (SAMLObjectBuilder<ConfirmationMethod>) getBuilderFactory().getBuilder(
138                 ConfirmationMethod.DEFAULT_ELEMENT_NAME);
139         subjectBuilder = (SAMLObjectBuilder<Subject>) getBuilderFactory().getBuilder(Subject.DEFAULT_ELEMENT_NAME);
140         statusBuilder = (SAMLObjectBuilder<Status>) getBuilderFactory().getBuilder(Status.DEFAULT_ELEMENT_NAME);
141         statusCodeBuilder = (SAMLObjectBuilder<StatusCode>) getBuilderFactory().getBuilder(
142                 StatusCode.DEFAULT_ELEMENT_NAME);
143         statusMessageBuilder = (SAMLObjectBuilder<StatusMessage>) getBuilderFactory().getBuilder(
144                 StatusMessage.DEFAULT_ELEMENT_NAME);
145         signatureBuilder = (XMLObjectBuilder<Signature>) getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
146     }
147
148     /**
149      * Checks that the SAML major version for a request is 1.
150      * 
151      * @param requestContext current request context containing the SAML message
152      * 
153      * @throws ProfileException thrown if the major version of the SAML request is not 1
154      */
155     protected void checkSamlVersion(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
156         SAMLObject samlObject = requestContext.getInboundSAMLMessage();
157
158         if (samlObject instanceof RequestAbstractType) {
159             RequestAbstractType request = (RequestAbstractType) samlObject;
160             if (request.getMajorVersion() < 1) {
161                 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER, StatusCode.REQUEST_VERSION_TOO_LOW,
162                         null));
163                 throw new ProfileException("SAML request major version too low");
164             } else if (request.getMajorVersion() > 1) {
165                 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER, StatusCode.REQUEST_VERSION_TOO_HIGH,
166                         null));
167                 throw new ProfileException("SAML request major version too low");
168             }
169         }
170     }
171
172     /**
173      * Builds a response to the attribute query within the request context.
174      * 
175      * @param requestContext current request context
176      * @param statements the statements to include in the response
177      * 
178      * @return the built response
179      * 
180      * @throws ProfileException thrown if there is a problem creating the SAML response
181      */
182     protected Response buildResponse(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, List<Statement> statements)
183             throws ProfileException {
184
185         DateTime issueInstant = new DateTime();
186
187         // create the assertion and add the attribute statement
188         Assertion assertion = buildAssertion(requestContext, issueInstant);
189         if (statements != null && !statements.isEmpty()) {
190             assertion.getStatements().addAll(statements);
191         }
192
193         // create the SAML response and add the assertion
194         Response samlResponse = responseBuilder.buildObject();
195         samlResponse.setIssueInstant(issueInstant);
196         populateStatusResponse(requestContext, samlResponse);
197
198         samlResponse.getAssertions().add(assertion);
199
200         // sign the assertion if it should be signed
201         signAssertion(requestContext, assertion);
202
203         Status status = buildStatus(StatusCode.SUCCESS, null, null);
204         samlResponse.setStatus(status);
205
206         return samlResponse;
207     }
208
209     /**
210      * Builds a basic assertion with its id, issue instant, SAML version, issuer, subject, and conditions populated.
211      * 
212      * @param requestContext current request context
213      * @param issueInstant time to use as assertion issue instant
214      * 
215      * @return the built assertion
216      */
217     protected Assertion buildAssertion(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
218         Assertion assertion = assertionBuilder.buildObject();
219         assertion.setID(getIdGenerator().generateIdentifier());
220         assertion.setIssueInstant(issueInstant);
221         assertion.setVersion(SAMLVersion.VERSION_11);
222         assertion.setIssuer(requestContext.getLocalEntityId());
223
224         Conditions conditions = buildConditions(requestContext, issueInstant);
225         assertion.setConditions(conditions);
226
227         return assertion;
228     }
229
230     /**
231      * Builds a SAML assertion condition set. The following fields are set; not before, not on or after, audience
232      * restrictions, and proxy restrictions.
233      * 
234      * @param requestContext current request context
235      * @param issueInstant timestamp the assertion was created
236      * 
237      * @return constructed conditions
238      */
239     protected Conditions buildConditions(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
240         AbstractSAML1ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
241
242         Conditions conditions = conditionsBuilder.buildObject();
243         conditions.setNotBefore(issueInstant);
244         conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
245
246         Collection<String> audiences;
247
248         // add audience restrictions
249         audiences = profileConfig.getAssertionAudiences();
250         if (audiences != null && audiences.size() > 0) {
251             AudienceRestrictionCondition audienceRestriction = audienceRestrictionConditionBuilder.buildObject();
252             for (String audienceUri : audiences) {
253                 Audience audience = audienceBuilder.buildObject();
254                 audience.setUri(audienceUri);
255                 audienceRestriction.getAudiences().add(audience);
256             }
257             conditions.getAudienceRestrictionConditions().add(audienceRestriction);
258         }
259
260         return conditions;
261     }
262
263     /**
264      * Builds the SAML subject for the user for the service provider.
265      * 
266      * @param requestContext current request context
267      * @param confirmationMethod subject confirmation method used for the subject
268      * 
269      * @return SAML subject for the user for the service provider
270      * 
271      * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
272      *             name ID attribute or because there are no supported name formats
273      */
274     protected Subject buildSubject(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, String confirmationMethod)
275             throws ProfileException {
276         NameIdentifier nameID = buildNameId(requestContext);
277         requestContext.setSubjectNameIdentifier(nameID);
278
279         ConfirmationMethod method = confirmationMethodBuilder.buildObject();
280         method.setConfirmationMethod(confirmationMethod);
281
282         SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
283         subjectConfirmation.getConfirmationMethods().add(method);
284
285         Subject subject = subjectBuilder.buildObject();
286         subject.setNameIdentifier(nameID);
287         subject.setSubjectConfirmation(subjectConfirmation);
288
289         return subject;
290     }
291
292     /**
293      * Builds a NameIdentifier appropriate for this request. NameIdentifier are built by inspecting the SAML request and
294      * metadata, picking a name format that was requested by the relying party or is mutually supported by both the
295      * relying party and asserting party as described in their metadata entries. Once a set of supported name formats is
296      * determined the principals attributes are inspected for an attribute supported an attribute encoder whose category
297      * is one of the supported name formats.
298      * 
299      * @param requestContext current request context
300      * 
301      * @return the NameIdentifier appropriate for this request
302      * 
303      * @throws ProfileException thrown if a NameIdentifier can not be created either because there was a problem
304      *             encoding the name ID attribute or because there are no supported name formats
305      */
306     protected NameIdentifier buildNameId(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext)
307             throws ProfileException {
308         log.debug("Building assertion NameIdentifier to relying party {} for principal {}", requestContext
309                 .getInboundMessageIssuer(), requestContext.getPrincipalName());
310         Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
311         if (principalAttributes == null || principalAttributes.isEmpty()) {
312             log.error("No attributes for principal {}, unable to construct of NameID", requestContext
313                     .getPrincipalName());
314             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
315                     "Unable to construct NameIdentifier"));
316             throw new ProfileException("No principal attributes support NameIdentifier construction");
317         }
318
319         List<String> supportedNameFormats = getNameFormats(requestContext);
320         if (supportedNameFormats == null || supportedNameFormats.isEmpty()) {
321             log.error("No common NameID formats supported by SP {} and IdP", requestContext.getInboundMessageIssuer());
322             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
323                     "Unable to construct NameIdentifier"));
324             throw new ProfileException("No principal attributes support NameIdentifier construction");
325         }
326
327         log.debug("Supported name formats: {}", supportedNameFormats);
328         try {
329             SAML1NameIdentifierEncoder nameIdEncoder;
330
331             for (BaseAttribute<?> attribute : principalAttributes.values()) {
332                 for (AttributeEncoder encoder : attribute.getEncoders()) {
333                     if (encoder instanceof SAML1NameIdentifierEncoder) {
334                         nameIdEncoder = (SAML1NameIdentifierEncoder) encoder;
335                         if (supportedNameFormats.contains(nameIdEncoder.getNameFormat())) {
336                             log.debug("Using attribute {} suppoting name format {} to create the NameIdentifier for principal",
337                                             attribute.getId(), nameIdEncoder.getNameFormat());
338                             return nameIdEncoder.encode(attribute);
339                         }
340                     }
341                 }
342             }
343             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
344                     "Unable to construct NameIdentifier"));
345             log.error("No principal attribute supports an encoding into a supported name ID format.");
346             throw new ProfileException("No principal attribute supports an encoding into a supported name ID format.");
347         } catch (AttributeEncodingException e) {
348             log.error("Unable to construct NameIdentifier", e);
349             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
350                     "Unable to construct NameIdentifier"));
351             throw new ProfileException("Unable to encode NameIdentifier attribute", e);
352         }
353
354     }
355
356     /**
357      * Gets the NameIdentifier format to use when creating NameIdentifiers for the relying party.
358      * 
359      * @param requestContext current request context
360      * 
361      * @return list of formats that may be used with the relying party
362      * 
363      * @throws ProfileException thrown if there is a problem determining the NameIdentifier format to use
364      */
365     protected List<String> getNameFormats(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext)
366             throws ProfileException {
367         ArrayList<String> nameFormats = new ArrayList<String>();
368
369         RoleDescriptor relyingPartyRole = requestContext.getPeerEntityRoleMetadata();
370         if (relyingPartyRole != null) {
371             List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
372             if (relyingPartySupportedFormats != null && !relyingPartySupportedFormats.isEmpty()) {
373                 nameFormats.addAll(relyingPartySupportedFormats);
374
375                 RoleDescriptor assertingPartyRole = requestContext.getLocalEntityRoleMetadata();
376                 if (assertingPartyRole != null) {
377                     List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
378                     if (assertingPartySupportedFormats != null && !assertingPartySupportedFormats.isEmpty()) {
379                         nameFormats.retainAll(assertingPartySupportedFormats);
380                     }
381                 }
382             }
383         }
384
385         if (nameFormats.isEmpty()) {
386             nameFormats.add("urn:oasis:names:tc:SAML:1.0:nameid-format:unspecified");
387         }
388
389         return nameFormats;
390     }
391
392     /**
393      * Gets the list of NameIdentifier formats supported for a given role.
394      * 
395      * @param role the role to get the list of supported NameIdentifier formats
396      * 
397      * @return list of supported NameIdentifier formats
398      */
399     protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
400         List<NameIDFormat> nameIDFormats = null;
401
402         if (role instanceof SSODescriptor) {
403             nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
404         } else if (role instanceof AuthnAuthorityDescriptor) {
405             nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
406         } else if (role instanceof PDPDescriptor) {
407             nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
408         } else if (role instanceof AttributeAuthorityDescriptor) {
409             nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
410         }
411
412         ArrayList<String> supportedFormats = new ArrayList<String>();
413         if (nameIDFormats != null) {
414             for (NameIDFormat format : nameIDFormats) {
415                 supportedFormats.add(format.getFormat());
416             }
417         }
418
419         return supportedFormats;
420     }
421
422     /**
423      * Constructs an SAML response message carrying a request error.
424      * 
425      * @param requestContext current request context containing the failure status
426      * 
427      * @return the constructed error response
428      */
429     protected Response buildErrorResponse(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) {
430         Response samlResponse = responseBuilder.buildObject();
431         samlResponse.setIssueInstant(new DateTime());
432         populateStatusResponse(requestContext, samlResponse);
433
434         samlResponse.setStatus(requestContext.getFailureStatus());
435
436         return samlResponse;
437     }
438
439     /**
440      * Populates the response's id, in response to, issue instant, version, and issuer properties.
441      * 
442      * @param requestContext current request context
443      * @param response the response to populate
444      */
445     protected void populateStatusResponse(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext,
446             ResponseAbstractType response) {
447         response.setID(getIdGenerator().generateIdentifier());
448
449         SAMLObject samlMessage = requestContext.getInboundSAMLMessage();
450         if (samlMessage != null && samlMessage instanceof RequestAbstractType) {
451             response.setInResponseTo(((RequestAbstractType) samlMessage).getID());
452         }
453         response.setVersion(SAMLVersion.VERSION_11);
454     }
455
456     /**
457      * Build a status message, with an optional second-level failure message.
458      * 
459      * @param topLevelCode top-level status code
460      * @param secondLevelCode second-level status code
461      * @param failureMessage An optional second-level failure message
462      * 
463      * @return a Status object.
464      */
465     protected Status buildStatus(QName topLevelCode, QName secondLevelCode, String failureMessage) {
466         Status status = statusBuilder.buildObject();
467
468         StatusCode statusCode = statusCodeBuilder.buildObject();
469         statusCode.setValue(topLevelCode);
470         status.setStatusCode(statusCode);
471
472         if (secondLevelCode != null) {
473             StatusCode secondLevelStatusCode = statusCodeBuilder.buildObject();
474             secondLevelStatusCode.setValue(secondLevelCode);
475             statusCode.setStatusCode(secondLevelStatusCode);
476         }
477
478         if (failureMessage != null) {
479             StatusMessage msg = statusMessageBuilder.buildObject();
480             msg.setMessage(failureMessage);
481             status.setStatusMessage(msg);
482         }
483
484         return status;
485     }
486
487     /**
488      * Resolved the attributes for the principal.
489      * 
490      * @param requestContext current request context
491      * 
492      * @throws ProfileException thrown if attributes can not be resolved
493      */
494     protected void resolveAttributes(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
495         AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
496         SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
497
498         try {
499             log.debug("Resolving attributes for principal {} of SAML request from relying party {}", requestContext
500                     .getPrincipalName(), requestContext.getInboundMessageIssuer());
501             Map<String, BaseAttribute> principalAttributes = attributeAuthority.getAttributes(requestContext);
502
503             requestContext.setAttributes(principalAttributes);
504         } catch (AttributeRequestException e) {
505             log.error("Error resolving attributes for SAML request from relying party "
506                     + requestContext.getInboundMessageIssuer(), e);
507             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error resolving attributes"));
508             throw new ProfileException("Error resolving attributes for SAML request from relying party "
509                     + requestContext.getInboundMessageIssuer(), e);
510         }
511     }
512
513     /**
514      * Executes a query for attributes and builds a SAML attribute statement from the results.
515      * 
516      * @param requestContext current request context
517      * @param subjectConfMethod subject confirmation method
518      * 
519      * @return attribute statement resulting from the query
520      * 
521      * @throws ProfileException thrown if there is a problem making the query
522      */
523     protected AttributeStatement buildAttributeStatement(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext,
524             String subjectConfMethod) throws ProfileException {
525
526         log.debug("Creating attribute statement in response to SAML request from relying party {}", requestContext
527                 .getInboundMessageIssuer());
528         AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
529         SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
530
531         try {
532             AttributeStatement statment;
533             if (requestContext.getInboundSAMLMessage() instanceof AttributeQuery) {
534                 statment = attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext
535                         .getInboundSAMLMessage(), requestContext.getPrincipalAttributes().values());
536             } else {
537                 statment = attributeAuthority.buildAttributeStatement(null, requestContext.getPrincipalAttributes()
538                         .values());
539             }
540
541             Subject statementSubject = buildSubject(requestContext, subjectConfMethod);
542             statment.setSubject(statementSubject);
543
544             return statment;
545         } catch (AttributeRequestException e) {
546             log.error("Error encoding attributes for principal " + requestContext.getPrincipalName(), e);
547             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error resolving attributes"));
548             throw new ProfileException("Error encoding attributes for principal " + requestContext.getPrincipalName(),
549                     e);
550         }
551     }
552
553     /**
554      * Resolves the principal name of the subject of the request.
555      * 
556      * @param requestContext current request context
557      * 
558      * @throws ProfileException thrown if the principal name can not be resolved
559      */
560     protected void resolvePrincipal(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
561         AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
562         SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
563
564         log.debug("Resolving principal name for subject of SAML request from relying party {}", requestContext
565                 .getInboundMessageIssuer());
566
567         try {
568             String principal = attributeAuthority.getPrincipal(requestContext);
569             requestContext.setPrincipalName(principal);
570         } catch (AttributeRequestException e) {
571             log.error("Error resolving attributes for SAML request from relying party "
572                     + requestContext.getInboundMessageIssuer(), e);
573             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
574                     "Error resolving principal"));
575             throw new ProfileException("Error resolving attributes for SAML request from relying party "
576                     + requestContext.getInboundMessageIssuer(), e);
577         }
578     }
579
580     /**
581      * Signs the given assertion if either the current profile configuration or the relying party configuration contains
582      * signing credentials.
583      * 
584      * @param requestContext current request context
585      * @param assertion assertion to sign
586      * 
587      * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
588      *             required, if a signing credential is not configured
589      */
590     protected void signAssertion(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, Assertion assertion)
591             throws ProfileException {
592         log.debug("Determining if SAML assertion to relying party {} should be signed", requestContext
593                 .getInboundMessageIssuer());
594
595         boolean signAssertion = false;
596
597         RoleDescriptor relyingPartyRole = requestContext.getPeerEntityRoleMetadata();
598         AbstractSAML1ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
599         if (profileConfig.getSignAssertions()) {
600             signAssertion = true;
601             log.debug("IdP relying party configuration {} indicates to sign assertions: {}", requestContext
602                     .getRelyingPartyConfiguration().getRelyingPartyId(), signAssertion);
603         }
604
605         if (!signAssertion && relyingPartyRole instanceof SPSSODescriptor) {
606             SPSSODescriptor ssoDescriptor = (SPSSODescriptor) relyingPartyRole;
607             if (ssoDescriptor.getWantAssertionsSigned() != null) {
608                 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
609                 log.debug("Entity metadata for relying party {} indicates to sign assertions: {}", requestContext
610                         .getInboundMessageIssuer(), signAssertion);
611             }
612         }
613
614         if (!signAssertion) {
615             return;
616         }
617
618         log.debug("Determining signing credntial for assertion to relying party {}", requestContext
619                 .getInboundMessageIssuer());
620         Credential signatureCredential = profileConfig.getSigningCredential();
621         if (signatureCredential == null) {
622             signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
623         }
624
625         if (signatureCredential == null) {
626             throw new ProfileException("No signing credential is specified for relying party configuration "
627                     + requestContext.getRelyingPartyConfiguration().getProviderId()
628                     + " or it's SAML2 attribute query profile configuration");
629         }
630
631         log.debug("Signing assertion to relying party {}", requestContext.getInboundMessageIssuer());
632         Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
633
634         signature.setSigningCredential(signatureCredential);
635         try {
636             // TODO pull SecurityConfiguration from SAMLMessageContext? needs to be added
637             // TODO how to pull what keyInfoGenName to use?
638             SecurityHelper.prepareSignatureParams(signature, signatureCredential, null, null);
639         } catch (SecurityException e) {
640             throw new ProfileException("Error preparing signature for signing", e);
641         }
642
643         assertion.setSignature(signature);
644
645         Marshaller assertionMarshaller = Configuration.getMarshallerFactory().getMarshaller(assertion);
646         try {
647             assertionMarshaller.marshall(assertion);
648             Signer.signObject(signature);
649         } catch (MarshallingException e) {
650             log.error("Unable to marshall assertion for signing", e);
651             throw new ProfileException("Unable to marshall assertion for signing", e);
652         }
653     }
654 }