Marshall assertions before trying to sign
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / AbstractSAML2ProfileHandler.java
index 004e90b..a96cf64 100644 (file)
@@ -21,15 +21,10 @@ import java.util.Collection;
 import java.util.List;
 import java.util.Map;
 
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-
-import org.apache.log4j.Logger;
 import org.joda.time.DateTime;
+import org.opensaml.Configuration;
 import org.opensaml.common.SAMLObjectBuilder;
 import org.opensaml.common.SAMLVersion;
-import org.opensaml.common.impl.SAMLObjectContentReference;
-import org.opensaml.log.Level;
 import org.opensaml.saml2.core.Assertion;
 import org.opensaml.saml2.core.AttributeQuery;
 import org.opensaml.saml2.core.AttributeStatement;
@@ -40,7 +35,6 @@ import org.opensaml.saml2.core.Conditions;
 import org.opensaml.saml2.core.Issuer;
 import org.opensaml.saml2.core.NameID;
 import org.opensaml.saml2.core.ProxyRestriction;
-import org.opensaml.saml2.core.RequestAbstractType;
 import org.opensaml.saml2.core.Response;
 import org.opensaml.saml2.core.Statement;
 import org.opensaml.saml2.core.Status;
@@ -49,18 +43,27 @@ import org.opensaml.saml2.core.StatusMessage;
 import org.opensaml.saml2.core.StatusResponseType;
 import org.opensaml.saml2.core.Subject;
 import org.opensaml.saml2.core.SubjectConfirmation;
+import org.opensaml.saml2.core.SubjectConfirmationData;
 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
 import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor;
+import org.opensaml.saml2.metadata.Endpoint;
 import org.opensaml.saml2.metadata.NameIDFormat;
 import org.opensaml.saml2.metadata.PDPDescriptor;
 import org.opensaml.saml2.metadata.RoleDescriptor;
 import org.opensaml.saml2.metadata.SPSSODescriptor;
 import org.opensaml.saml2.metadata.SSODescriptor;
+import org.opensaml.ws.transport.http.HTTPInTransport;
 import org.opensaml.xml.XMLObjectBuilder;
+import org.opensaml.xml.io.Marshaller;
+import org.opensaml.xml.io.MarshallingException;
+import org.opensaml.xml.security.SecurityException;
+import org.opensaml.xml.security.SecurityHelper;
 import org.opensaml.xml.security.credential.Credential;
 import org.opensaml.xml.signature.Signature;
 import org.opensaml.xml.signature.Signer;
 import org.opensaml.xml.util.DatatypeHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import edu.internet2.middleware.shibboleth.common.attribute.AttributeRequestException;
 import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
@@ -68,15 +71,9 @@ import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEn
 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncodingException;
 import edu.internet2.middleware.shibboleth.common.attribute.encoding.SAML2NameIDAttributeEncoder;
 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML2AttributeAuthority;
-import edu.internet2.middleware.shibboleth.common.attribute.provider.ShibbolethSAMLAttributeRequestContext;
-import edu.internet2.middleware.shibboleth.common.log.AuditLogEntry;
 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
-import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
-import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AbstractSAML2ProfileConfiguration;
 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
-import edu.internet2.middleware.shibboleth.idp.session.ServiceInformation;
-import edu.internet2.middleware.shibboleth.idp.session.Session;
 
 /** Common implementation details for profile handlers. */
 public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHandler {
@@ -85,7 +82,7 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
     public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_20;
 
     /** Class logger. */
-    private Logger log = Logger.getLogger(AbstractSAML2ProfileHandler.class);
+    private Logger log = LoggerFactory.getLogger(AbstractSAML2ProfileHandler.class);
 
     /** For building response. */
     private SAMLObjectBuilder<Response> responseBuilder;
@@ -108,9 +105,12 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
     /** For building subject. */
     private SAMLObjectBuilder<Subject> subjectBuilder;
 
-    /** For builder subject confirmation. */
+    /** For building subject confirmation. */
     private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
 
+    /** For building subject confirmation data. */
+    private SAMLObjectBuilder<SubjectConfirmationData> subjectConfirmationDataBuilder;
+
     /** For building conditions. */
     private SAMLObjectBuilder<Conditions> conditionsBuilder;
 
@@ -143,6 +143,8 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
         subjectBuilder = (SAMLObjectBuilder<Subject>) getBuilderFactory().getBuilder(Subject.DEFAULT_ELEMENT_NAME);
         subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) getBuilderFactory().getBuilder(
                 SubjectConfirmation.DEFAULT_ELEMENT_NAME);
+        subjectConfirmationDataBuilder = (SAMLObjectBuilder<SubjectConfirmationData>) getBuilderFactory().getBuilder(
+                SubjectConfirmationData.DEFAULT_ELEMENT_NAME);
         conditionsBuilder = (SAMLObjectBuilder<Conditions>) getBuilderFactory().getBuilder(
                 Conditions.DEFAULT_ELEMENT_NAME);
         audienceRestrictionBuilder = (SAMLObjectBuilder<AudienceRestriction>) getBuilderFactory().getBuilder(
@@ -160,8 +162,8 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
      * 
      * @throws ProfileException thrown if the major version of the SAML request is not 2
      */
-    protected void checkSamlVersion(SAML2ProfileRequestContext requestContext) throws ProfileException {
-        SAMLVersion version = requestContext.getSamlRequest().getVersion();
+    protected void checkSamlVersion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
+        SAMLVersion version = requestContext.getInboundSAMLMessage().getVersion();
         if (version.getMajorVersion() < 2) {
             requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
                     StatusCode.REQUEST_VERSION_TOO_LOW_URI, null));
@@ -177,21 +179,23 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
      * Builds a response to the attribute query within the request context.
      * 
      * @param requestContext current request context
-     * @param assertionSubject subject of the assertion within the response
+     * @param subjectConfirmationMethod confirmation method used for the subject
      * @param statements the statements to include in the response
      * 
      * @return the built response
      * 
      * @throws ProfileException thrown if there is a problem creating the SAML response
      */
-    protected Response buildResponse(SAML2ProfileRequestContext requestContext, Subject assertionSubject,
-            List<Statement> statements) throws ProfileException {
+    protected Response buildResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext,
+            String subjectConfirmationMethod, List<Statement> statements) throws ProfileException {
 
         DateTime issueInstant = new DateTime();
 
+        Subject subject = buildSubject(requestContext, subjectConfirmationMethod, issueInstant);
+
         // create the assertion and add the attribute statement
         Assertion assertion = buildAssertion(requestContext, issueInstant);
-        assertion.setSubject(assertionSubject);
+        assertion.setSubject(subject);
         if (statements != null) {
             assertion.getStatements().addAll(statements);
         }
@@ -220,7 +224,7 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
      * 
      * @return the built assertion
      */
-    protected Assertion buildAssertion(SAML2ProfileRequestContext requestContext, DateTime issueInstant) {
+    protected Assertion buildAssertion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
         Assertion assertion = assertionBuilder.buildObject();
         assertion.setID(getIdGenerator().generateIdentifier());
         assertion.setIssueInstant(issueInstant);
@@ -240,10 +244,10 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
      * 
      * @return the built issuer
      */
-    protected Issuer buildEntityIssuer(SAML2ProfileRequestContext requestContext) {
+    protected Issuer buildEntityIssuer(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) {
         Issuer issuer = issuerBuilder.buildObject();
         issuer.setFormat(Issuer.ENTITY);
-        issuer.setValue(requestContext.getAssertingPartyId());
+        issuer.setValue(requestContext.getLocalEntityId());
 
         return issuer;
     }
@@ -257,7 +261,7 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
      * 
      * @return constructed conditions
      */
-    protected Conditions buildConditions(SAML2ProfileRequestContext requestContext, DateTime issueInstant) {
+    protected Conditions buildConditions(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
         AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
 
         Conditions conditions = conditionsBuilder.buildObject();
@@ -302,16 +306,44 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
      * @param requestContext current request context
      * @param response the response to populate
      */
-    protected void populateStatusResponse(SAML2ProfileRequestContext requestContext, StatusResponseType response) {
+    protected void populateStatusResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext,
+            StatusResponseType response) {
         response.setID(getIdGenerator().generateIdentifier());
-        if (requestContext.getSamlRequest() != null) {
-            response.setInResponseTo(requestContext.getSamlRequest().getID());
+        if (requestContext.getInboundSAMLMessage() != null) {
+            response.setInResponseTo(requestContext.getInboundSAMLMessageId());
         }
         response.setVersion(SAMLVersion.VERSION_20);
         response.setIssuer(buildEntityIssuer(requestContext));
     }
 
     /**
+     * Resolves the attributes for the principal.
+     * 
+     * @param requestContext current request context
+     * 
+     * @throws ProfileException thrown if there is a problem resolved attributes
+     */
+    protected void resolveAttributes(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
+        AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
+        SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
+
+        try {
+            log.debug("Resolving attributes for principal {} of SAML request from relying party {}", requestContext
+                    .getPrincipalName(), requestContext.getInboundMessageIssuer());
+            Map<String, BaseAttribute> principalAttributes = attributeAuthority.getAttributes(requestContext);
+
+            requestContext.setAttributes(principalAttributes);
+        } catch (AttributeRequestException e) {
+            log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
+                    + " from relying party " + requestContext.getInboundMessageIssuer(), e);
+            requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
+            throw new ProfileException("Error resolving attributes for SAML request "
+                    + requestContext.getInboundSAMLMessageId() + " from relying party "
+                    + requestContext.getInboundMessageIssuer(), e);
+        }
+    }
+
+    /**
      * Executes a query for attributes and builds a SAML attribute statement from the results.
      * 
      * @param requestContext current request context
@@ -320,42 +352,26 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
      * 
      * @throws ProfileException thrown if there is a problem making the query
      */
-    protected AttributeStatement buildAttributeStatement(SAML2ProfileRequestContext requestContext)
+    protected AttributeStatement buildAttributeStatement(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
             throws ProfileException {
-
-        if (log.isDebugEnabled()) {
-            log.debug("Creating attribute statement in response to SAML request "
-                    + requestContext.getSamlRequest().getID() + " from relying party "
-                    + requestContext.getRelyingPartyId());
-        }
+        log.debug("Creating attribute statement in response to SAML request {} from relying party {}", requestContext
+                .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
 
         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
-
         try {
-            if (log.isDebugEnabled()) {
-                log.debug("Resolving attributes for principal " + requestContext.getPrincipalName()
-                        + " of SAML request " + requestContext.getSamlRequest().getID() + " from relying party "
-                        + requestContext.getRelyingPartyId());
-            }
-            Map<String, BaseAttribute> principalAttributes = attributeAuthority
-                    .getAttributes(buildAttributeRequestContext(requestContext));
-
-            requestContext.setPrincipalAttributes(principalAttributes);
-
-            if (requestContext.getSamlRequest() instanceof AttributeQuery) {
-                return attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext.getSamlRequest(),
-                        principalAttributes.values());
+            if (requestContext.getInboundSAMLMessage() instanceof AttributeQuery) {
+                return attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext
+                        .getInboundSAMLMessage(), requestContext.getPrincipalAttributes().values());
             } else {
-                return attributeAuthority.buildAttributeStatement(null, principalAttributes.values());
+                return attributeAuthority.buildAttributeStatement(null, requestContext.getPrincipalAttributes()
+                        .values());
             }
         } catch (AttributeRequestException e) {
-            log.error("Error resolving attributes for SAML request " + requestContext.getSamlRequest().getID()
-                    + " from relying party " + requestContext.getRelyingPartyId(), e);
+            log.error("Error encoding attributes for principal " + requestContext.getPrincipalName(), e);
             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
-            throw new ProfileException("Error resolving attributes for SAML request "
-                    + requestContext.getSamlRequest().getID() + " from relying party "
-                    + requestContext.getRelyingPartyId(), e);
+            throw new ProfileException("Error encoding attributes for principal " + requestContext.getPrincipalName(),
+                    e);
         }
     }
 
@@ -366,74 +382,36 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
      * 
      * @throws ProfileException thrown if the principal name can not be resolved
      */
-    protected void resolvePrincipal(SAML2ProfileRequestContext requestContext) throws ProfileException {
+    protected void resolvePrincipal(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
         if (profileConfiguration == null) {
             log.error("Unable to resolve principal, no SAML 2 profile configuration for relying party "
-                    + requestContext.getRelyingPartyId());
+                    + requestContext.getInboundMessageIssuer());
             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
                     "Error resolving principal"));
             throw new ProfileException(
                     "Unable to resolve principal, no SAML 2 profile configuration for relying party "
-                            + requestContext.getRelyingPartyId());
+                            + requestContext.getInboundMessageIssuer());
         }
         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
-
-        if (log.isDebugEnabled()) {
-            log.debug("Resolving principal name for subject of SAML request " + requestContext.getSamlRequest().getID()
-                    + " from relying party " + requestContext.getRelyingPartyId());
-        }
+        log.debug("Resolving principal name for subject of SAML request {} from relying party {}", requestContext
+                .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
 
         try {
-            String principal = attributeAuthority.getPrincipal(buildAttributeRequestContext(requestContext));
+            String principal = attributeAuthority.getPrincipal(requestContext);
             requestContext.setPrincipalName(principal);
         } catch (AttributeRequestException e) {
-            log.error("Error resolving attributes for SAML request " + requestContext.getSamlRequest().getID()
-                    + " from relying party " + requestContext.getRelyingPartyId(), e);
+            log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
+                    + " from relying party " + requestContext.getInboundMessageIssuer(), e);
             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.UNKNOWN_PRINCIPAL_URI,
                     "Error resolving principal"));
             throw new ProfileException("Error resolving attributes for SAML request "
-                    + requestContext.getSamlRequest().getID() + " from relying party "
-                    + requestContext.getRelyingPartyId(), e);
+                    + requestContext.getInboundSAMLMessageId() + " from relying party "
+                    + requestContext.getInboundMessageIssuer(), e);
         }
     }
 
     /**
-     * Creates an attribute query context from the current profile request context.
-     * 
-     * @param requestContext current profile request
-     * 
-     * @return created query context
-     */
-    protected ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery> buildAttributeRequestContext(
-            SAML2ProfileRequestContext requestContext) {
-
-        ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery> queryContext;
-
-        queryContext = new ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery>(getMetadataProvider(),
-                requestContext.getRelyingPartyConfiguration(), (AttributeQuery) requestContext.getSamlRequest());
-        queryContext.setAttributeRequester(requestContext.getAssertingPartyId());
-        queryContext.setPrincipalName(requestContext.getPrincipalName());
-        queryContext.setProfileConfiguration(requestContext.getProfileConfiguration());
-        queryContext.setRequest(requestContext.getProfileRequest());
-
-        Session userSession = getSessionManager().getSession(getUserSessionId(requestContext.getProfileRequest()));
-        if (userSession != null) {
-            queryContext.setUserSession(userSession);
-            ServiceInformation serviceInfo = userSession.getServicesInformation().get(
-                    requestContext.getRelyingPartyId());
-            if (serviceInfo != null) {
-                String principalAuthenticationMethod = serviceInfo.getAuthenticationMethod().getAuthenticationMethod();
-
-                requestContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
-                queryContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
-            }
-        }
-
-        return queryContext;
-    }
-
-    /**
      * Signs the given assertion if either the current profile configuration or the relying party configuration contains
      * signing credentials.
      * 
@@ -443,41 +421,35 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
      * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
      *             required, if a signing credential is not configured
      */
-    protected void signAssertion(SAML2ProfileRequestContext requestContext, Assertion assertion)
+    protected void signAssertion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, Assertion assertion)
             throws ProfileException {
-        if (log.isDebugEnabled()) {
-            log.debug("Determining if SAML assertion to relying party " + requestContext.getRelyingPartyId()
-                    + " should be signed");
-        }
+        log.debug("Determining if SAML assertion to relying party {} should be signed", requestContext
+                .getInboundMessageIssuer());
 
         boolean signAssertion = false;
 
         AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
+        if (profileConfig.getSignAssertions()) {
+            signAssertion = true;
+            log.debug("IdP relying party configuration {} indicates to sign assertions: {}", requestContext
+                    .getRelyingPartyConfiguration().getRelyingPartyId(), signAssertion);
+        }
 
-        if (requestContext.getRelyingPartyRoleMetadata() instanceof SPSSODescriptor) {
-            SPSSODescriptor ssoDescriptor = (SPSSODescriptor) requestContext.getRelyingPartyRoleMetadata();
+        if (!signAssertion && requestContext.getPeerEntityRoleMetadata() instanceof SPSSODescriptor) {
+            SPSSODescriptor ssoDescriptor = (SPSSODescriptor) requestContext.getPeerEntityRoleMetadata();
             if (ssoDescriptor.getWantAssertionsSigned() != null) {
                 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
-                if (log.isDebugEnabled()) {
-                    log.debug("Entity metadata for relying party " + requestContext.getRelyingPartyId()
-                            + " indicates to sign assertions: " + signAssertion);
-                }
+                log.debug("Entity metadata for relying party {} indicates to sign assertions: {}", requestContext
+                        .getInboundMessageIssuer(), signAssertion);
             }
-        } else if (profileConfig.getSignAssertions()) {
-            signAssertion = true;
-            log.debug("IdP relying party configuration "
-                    + requestContext.getRelyingPartyConfiguration().getRelyingPartyId()
-                    + " indicates to sign assertions: " + signAssertion);
         }
 
         if (!signAssertion) {
             return;
         }
 
-        if (log.isDebugEnabled()) {
-            log.debug("Determining signing credntial for assertion to relying party "
-                    + requestContext.getRelyingPartyId());
-        }
+        log.debug("Determining signing credntial for assertion to relying party {}", requestContext
+                .getInboundMessageIssuer());
         Credential signatureCredential = profileConfig.getSigningCredential();
         if (signatureCredential == null) {
             signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
@@ -489,15 +461,28 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
                     + " or it's SAML2 attribute query profile configuration");
         }
 
-        if (log.isDebugEnabled()) {
-            log.debug("Signing assertion to relying party " + requestContext.getRelyingPartyId());
-        }
-        SAMLObjectContentReference contentRef = new SAMLObjectContentReference(assertion);
+        log.debug("Signing assertion to relying party {}", requestContext.getInboundMessageIssuer());
         Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
-        signature.getContentReferences().add(contentRef);
+
+        signature.setSigningCredential(signatureCredential);
+        try {
+            // TODO pull SecurityConfiguration from SAMLMessageContext? needs to be added
+            // TODO how to pull what keyInfoGenName to use?
+            SecurityHelper.prepareSignatureParams(signature, signatureCredential, null, null);
+        } catch (SecurityException e) {
+            throw new ProfileException("Error preparing signature for signing", e);
+        }
+
         assertion.setSignature(signature);
 
-        Signer.signObject(signature);
+        Marshaller assertionMarshaller = Configuration.getMarshallerFactory().getMarshaller(assertion);
+        try {
+            assertionMarshaller.marshall(assertion);
+            Signer.signObject(signature);
+        } catch (MarshallingException e) {
+            log.error("Unable to marshall assertion for signing", e);
+            throw new ProfileException("Unable to marshall assertion for signing", e);
+        }
     }
 
     /**
@@ -537,20 +522,38 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
      * 
      * @param requestContext current request context
      * @param confirmationMethod subject confirmation method used for the subject
+     * @param issueInstant instant the subject confirmation data should reflect for issuance
      * 
      * @return SAML subject for the user for the service provider
      * 
      * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
      *             name ID attribute or because there are no supported name formats
      */
-    protected Subject buildSubject(SAML2ProfileRequestContext requestContext, String confirmationMethod)
-            throws ProfileException {
+    protected Subject buildSubject(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, String confirmationMethod,
+            DateTime issueInstant) throws ProfileException {
         NameID nameID = buildNameId(requestContext);
-        requestContext.setSubjectNameID(nameID);
+        requestContext.setSubjectNameIdentifier(nameID);
         // TODO handle encryption
 
+        SubjectConfirmationData confirmationData = subjectConfirmationDataBuilder.buildObject();
+        HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
+        confirmationData.setAddress(inTransport.getPeerAddress());
+        confirmationData.setInResponseTo(requestContext.getInboundSAMLMessageId());
+        confirmationData.setNotOnOrAfter(issueInstant.plus(requestContext.getProfileConfiguration()
+                .getAssertionLifetime()));
+
+        Endpoint relyingPartyEndpoint = requestContext.getPeerEntityEndpoint();
+        if (relyingPartyEndpoint != null) {
+            if (relyingPartyEndpoint.getResponseLocation() != null) {
+                confirmationData.setRecipient(relyingPartyEndpoint.getResponseLocation());
+            } else {
+                confirmationData.setRecipient(relyingPartyEndpoint.getLocation());
+            }
+        }
+
         SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
         subjectConfirmation.setMethod(confirmationMethod);
+        subjectConfirmation.setSubjectConfirmationData(confirmationData);
 
         Subject subject = subjectBuilder.buildObject();
         subject.setNameID(nameID);
@@ -573,20 +576,16 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
      * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
      *             name ID attribute or because there are no supported name formats
      */
-    protected NameID buildNameId(SAML2ProfileRequestContext requestContext) throws ProfileException {
-        if (log.isDebugEnabled()) {
-            log.debug("Building assertion NameID for principal/relying party:" + requestContext.getPrincipalName()
-                    + "/" + requestContext.getRelyingPartyId());
-        }
+    protected NameID buildNameId(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
+        log.debug("Building assertion NameID for principal/relying party:{}/{}", requestContext.getPrincipalName(),
+                requestContext.getInboundMessageIssuer());
         Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
         List<String> supportedNameFormats = getNameFormats(requestContext);
 
-        if (log.isDebugEnabled()) {
-            log.debug("Supported NameID formats: " + supportedNameFormats);
-        }
+        log.debug("Supported NameID formats: {}", supportedNameFormats);
 
         if (principalAttributes == null || supportedNameFormats == null) {
-            log.error("No attributes for principal " + requestContext.getPrincipalName() 
+            log.error("No attributes for principal " + requestContext.getPrincipalName()
                     + " support constructions of NameID");
             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
                     "Unable to construct NameID"));
@@ -600,19 +599,20 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
                     if (encoder instanceof SAML2NameIDAttributeEncoder) {
                         nameIdEncoder = (SAML2NameIDAttributeEncoder) encoder;
                         if (supportedNameFormats.contains(nameIdEncoder.getNameFormat())) {
-                            if (log.isDebugEnabled()) {
-                                log.debug("Using attribute " + attribute.getId() + " suppoting NameID format "
-                                        + nameIdEncoder.getNameFormat() + " to create the NameID for principal "
-                                        + requestContext.getPrincipalName());
-                            }
+                            log
+                                    .debug(
+                                            "Using attribute {} suppoting NameID format {} to create the NameID for principal.{}",
+                                            attribute.getId(), nameIdEncoder.getNameFormat());
                             return nameIdEncoder.encode(attribute);
                         }
                     }
                 }
             }
+            log.error("No principal attribute supported encoding into a supported name ID format.");
             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
-            throw new ProfileException("No principal attribute supported encoding into the a supported name ID format.");
+            throw new ProfileException("No principal attribute supported encoding into a supported name ID format.");
         } catch (AttributeEncodingException e) {
+            log.error("Unable to encode NameID attribute", e);
             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
             throw new ProfileException("Unable to encode NameID attribute", e);
         }
@@ -627,38 +627,51 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
      * 
      * @throws ProfileException thrown if there is a problem determing the NameID format to use
      */
-    protected List<String> getNameFormats(SAML2ProfileRequestContext requestContext) throws ProfileException {
+    protected List<String> getNameFormats(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
+            throws ProfileException {
         ArrayList<String> nameFormats = new ArrayList<String>();
 
-        List<String> assertingPartySupportedFormats = getEntitySupportedFormats(requestContext
-                .getAssertingPartyRoleMetadata());
-
-        String nameFormat = null;
-        if (requestContext.getSamlRequest() instanceof AuthnRequest) {
-            AuthnRequest authnRequest = (AuthnRequest) requestContext.getSamlRequest();
-            if (authnRequest.getNameIDPolicy() != null) {
-                nameFormat = authnRequest.getNameIDPolicy().getFormat();
-                if (assertingPartySupportedFormats.contains(nameFormat)) {
-                    nameFormats.add(nameFormat);
-                } else {
-                    requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
-                            StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
-                    throw new ProfileException("NameID format required by relying party is not supported");
+        // Determine name formats supported by both SP and IdP
+        RoleDescriptor relyingPartyRole = requestContext.getPeerEntityRoleMetadata();
+        if (relyingPartyRole != null) {
+            List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
+            if (relyingPartySupportedFormats != null && !relyingPartySupportedFormats.isEmpty()) {
+                nameFormats.addAll(relyingPartySupportedFormats);
+
+                RoleDescriptor assertingPartyRole = requestContext.getLocalEntityRoleMetadata();
+                if (assertingPartyRole != null) {
+                    List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
+                    if (assertingPartySupportedFormats != null && !assertingPartySupportedFormats.isEmpty()) {
+                        nameFormats.retainAll(assertingPartySupportedFormats);
+                    }
                 }
             }
         }
 
         if (nameFormats.isEmpty()) {
-            List<String> relyingPartySupportedFormats = getEntitySupportedFormats(requestContext
-                    .getRelyingPartyRoleMetadata());
-
-            assertingPartySupportedFormats.retainAll(relyingPartySupportedFormats);
-            nameFormats.addAll(assertingPartySupportedFormats);
-        }
-        if (nameFormats.isEmpty()) {
             nameFormats.add("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
         }
 
+        // If authn request and name ID policy format specified, make sure it's in the list of supported formats
+        String nameFormat = null;
+        if (requestContext.getInboundSAMLMessage() instanceof AuthnRequest) {
+            AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
+            if (authnRequest.getNameIDPolicy() != null) {
+                nameFormat = DatatypeHelper.safeTrimOrNullString(authnRequest.getNameIDPolicy().getFormat());
+                if (nameFormat != null) {
+                    if (nameFormats.contains(nameFormat)) {
+                        nameFormats.clear();
+                        nameFormats.add(nameFormat);
+                    } else {
+                        requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
+                                StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
+                        throw new ProfileException("NameID format required by relying party is not supported");
+                    }
+                }
+
+            }
+        }
+
         return nameFormats;
     }
 
@@ -699,7 +712,7 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
      * 
      * @return the constructed error response
      */
-    protected Response buildErrorResponse(SAML2ProfileRequestContext requestContext) {
+    protected Response buildErrorResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) {
         Response samlResponse = responseBuilder.buildObject();
         samlResponse.setIssueInstant(new DateTime());
         populateStatusResponse(requestContext, samlResponse);
@@ -708,153 +721,4 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
 
         return samlResponse;
     }
-
-    /**
-     * Writes an aduit log entry indicating the successful response to the attribute request.
-     * 
-     * @param context current request context
-     */
-    protected void writeAuditLogEntry(SAML2ProfileRequestContext context) {
-        AuditLogEntry auditLogEntry = new AuditLogEntry();
-        auditLogEntry.setMessageProfile(getProfileId());
-        auditLogEntry.setPrincipalAuthenticationMethod(context.getPrincipalAuthenticationMethod());
-        auditLogEntry.setPrincipalName(context.getPrincipalName());
-        auditLogEntry.setAssertingPartyId(context.getAssertingPartyId());
-        auditLogEntry.setRelyingPartyId(context.getRelyingPartyId());
-        auditLogEntry.setRequestBinding(context.getMessageDecoder().getBindingURI());
-        auditLogEntry.setRequestId(context.getSamlRequest().getID());
-        auditLogEntry.setResponseBinding(context.getMessageEncoder().getBindingURI());
-        auditLogEntry.setResponseId(context.getSamlResponse().getID());
-        if(context.getPrincipalAttributes() != null){
-            auditLogEntry.getReleasedAttributes().addAll(context.getPrincipalAttributes().keySet());
-        }
-        getAduitLog().log(Level.CRITICAL, auditLogEntry);
-    }
-
-    /**
-     * Contextual object used to accumlate information as profile requests are being processed.
-     * 
-     * @param <RequestType> type of SAML 2 request
-     * @param <ResponseType> type of SAML 2 response
-     * @param <ProfileConfigurationType> configuration type for this profile
-     */
-    protected class SAML2ProfileRequestContext<RequestType extends RequestAbstractType, ResponseType extends StatusResponseType, ProfileConfigurationType extends AbstractSAML2ProfileConfiguration>
-            extends SAMLProfileRequestContext {
-
-        /** SAML request message. */
-        private RequestType samlRequest;
-
-        /** SAML response message. */
-        private ResponseType samlResponse;
-
-        /** Request profile configuration. */
-        private ProfileConfigurationType profileConfiguration;
-
-        /** The NameID of the subject of this request. */
-        private NameID subjectNameID;
-
-        /** The request failure status. */
-        private Status failureStatus;
-
-        /**
-         * Constructor.
-         * 
-         * @param request current profile request
-         * @param response current profile response
-         */
-        public SAML2ProfileRequestContext(ProfileRequest<ServletRequest> request,
-                ProfileResponse<ServletResponse> response) {
-            super(request, response);
-        }
-
-        /**
-         * Gets the NameID of the subject of this request.
-         * 
-         * @return NameID of the subject of this request
-         */
-        public NameID getSubjectNameID() {
-            return subjectNameID;
-        }
-
-        /**
-         * Sets the NameID of the subject of this request.
-         * 
-         * @param nameID NameID of the subject of this request
-         */
-        public void setSubjectNameID(NameID nameID) {
-            subjectNameID = nameID;
-        }
-
-        /**
-         * Gets the profile configuration for this request.
-         * 
-         * @return profile configuration for this request
-         */
-        public ProfileConfigurationType getProfileConfiguration() {
-            return profileConfiguration;
-        }
-
-        /**
-         * Sets the profile configuration for this request.
-         * 
-         * @param configuration profile configuration for this request
-         */
-        public void setProfileConfiguration(ProfileConfigurationType configuration) {
-            profileConfiguration = configuration;
-        }
-
-        /**
-         * Gets the SAML request message.
-         * 
-         * @return SAML request message
-         */
-        public RequestType getSamlRequest() {
-            return samlRequest;
-        }
-
-        /**
-         * Sets the SAML request message.
-         * 
-         * @param request SAML request message
-         */
-        public void setSamlRequest(RequestType request) {
-            samlRequest = request;
-        }
-
-        /**
-         * Gets the SAML response message.
-         * 
-         * @return SAML response message
-         */
-        public ResponseType getSamlResponse() {
-            return samlResponse;
-        }
-
-        /**
-         * Sets the SAML response message.
-         * 
-         * @param response SAML response message
-         */
-        public void setSamlResponse(ResponseType response) {
-            samlResponse = response;
-        }
-
-        /**
-         * Gets the status reflecting a request failure.
-         * 
-         * @return status reflecting a request failure
-         */
-        public Status getFailureStatus() {
-            return failureStatus;
-        }
-
-        /**
-         * Sets the status reflecting a request failure.
-         * 
-         * @param status status reflecting a request failure
-         */
-        public void setFailureStatus(Status status) {
-            failureStatus = status;
-        }
-    }
 }
\ No newline at end of file