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