Set communication profile before decoding
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / SSOProfileHandler.java
index 6a47578..0a0aea6 100644 (file)
@@ -18,23 +18,14 @@ package edu.internet2.middleware.shibboleth.idp.profile.saml2;
 
 import java.io.IOException;
 import java.util.ArrayList;
-import java.util.List;
 
 import javax.servlet.RequestDispatcher;
 import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
 import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
 
-import org.apache.log4j.Logger;
 import org.opensaml.common.SAMLObjectBuilder;
-import org.opensaml.common.binding.BindingException;
-import org.opensaml.common.binding.decoding.MessageDecoder;
-import org.opensaml.common.binding.encoding.MessageEncoder;
-import org.opensaml.common.binding.security.SAMLSecurityPolicy;
+import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
 import org.opensaml.common.xml.SAMLConstants;
-import org.opensaml.saml2.core.SubjectLocality;
 import org.opensaml.saml2.binding.AuthnResponseEndpointSelector;
 import org.opensaml.saml2.core.AttributeStatement;
 import org.opensaml.saml2.core.AuthnContext;
@@ -46,27 +37,41 @@ import org.opensaml.saml2.core.RequestedAuthnContext;
 import org.opensaml.saml2.core.Response;
 import org.opensaml.saml2.core.Statement;
 import org.opensaml.saml2.core.StatusCode;
+import org.opensaml.saml2.core.Subject;
+import org.opensaml.saml2.core.SubjectLocality;
 import org.opensaml.saml2.metadata.AssertionConsumerService;
 import org.opensaml.saml2.metadata.Endpoint;
-import org.opensaml.saml2.metadata.provider.MetadataProviderException;
-import org.opensaml.ws.security.SecurityPolicyException;
+import org.opensaml.saml2.metadata.EntityDescriptor;
+import org.opensaml.saml2.metadata.IDPSSODescriptor;
+import org.opensaml.saml2.metadata.SPSSODescriptor;
+import org.opensaml.ws.message.decoder.MessageDecodingException;
+import org.opensaml.ws.transport.http.HTTPInTransport;
+import org.opensaml.ws.transport.http.HTTPOutTransport;
+import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
+import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
 import org.opensaml.xml.io.MarshallingException;
 import org.opensaml.xml.io.UnmarshallingException;
+import org.opensaml.xml.security.SecurityException;
+import org.opensaml.xml.util.DatatypeHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 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.profile.provider.BaseSAMLProfileRequestContext;
+import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
+import edu.internet2.middleware.shibboleth.idp.authn.PassiveAuthenticationException;
 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
+import edu.internet2.middleware.shibboleth.idp.session.Session;
 
 /** SAML 2.0 SSO request profile handler. */
 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
 
     /** Class logger. */
-    private final Logger log = Logger.getLogger(SSOProfileHandler.class);
+    private final Logger log = LoggerFactory.getLogger(SSOProfileHandler.class);
 
     /** Builder of AuthnStatement objects. */
     private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
@@ -83,37 +88,22 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
     /** Builder of SubjectLocality objects. */
     private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
 
+    /** Builder of Endpoint objects. */
+    private SAMLObjectBuilder<Endpoint> endpointBuilder;
+
     /** URL of the authentication manager servlet. */
     private String authenticationManagerPath;
-    
-    /** URI of SAML 2 bindings supported for outgoing messaged encoding. */
-    private ArrayList<String> supportedOutgoingBindings;
-
-    /** URI of request decoder. */
-    private String decodingBinding;
 
     /**
      * Constructor.
      * 
      * @param authnManagerPath path to the authentication manager servlet
-     * @param outgoingBindings URIs of SAML 2 bindings supported for outgoing message encoding
-     * @param decoder URI of the request decoder to use
      */
     @SuppressWarnings("unchecked")
-    public SSOProfileHandler(String authnManagerPath, List<String> outgoingBindings, String decoder) {
+    public SSOProfileHandler(String authnManagerPath) {
         super();
 
-        if (authnManagerPath == null || decoder == null) {
-            throw new IllegalArgumentException("AuthN manager path or decoding bindings URI may not be null");
-        }
         authenticationManagerPath = authnManagerPath;
-        
-        if(outgoingBindings == null || outgoingBindings.isEmpty()){
-            throw new IllegalArgumentException("List of supported outgoing bindings may not be empty");
-        }
-        supportedOutgoingBindings = new ArrayList<String>(outgoingBindings);
-        
-        decodingBinding = decoder;
 
         authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) getBuilderFactory().getBuilder(
                 AuthnStatement.DEFAULT_ELEMENT_NAME);
@@ -125,22 +115,26 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
                 AuthnContextDeclRef.DEFAULT_ELEMENT_NAME);
         subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
                 SubjectLocality.DEFAULT_ELEMENT_NAME);
+        endpointBuilder = (SAMLObjectBuilder<Endpoint>) getBuilderFactory().getBuilder(
+                AssertionConsumerService.DEFAULT_ELEMENT_NAME);
     }
 
     /** {@inheritDoc} */
     public String getProfileId() {
-        return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:sso";
+        return SSOConfiguration.PROFILE_ID;
     }
 
     /** {@inheritDoc} */
-    public void processRequest(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
-            throws ProfileException {
+    public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
+        HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
 
-        HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
-        if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
-            performAuthentication(request, response);
+        LoginContext loginContext = (LoginContext) servletRequest.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
+        if (loginContext == null) {
+            log.debug("Incoming request does not contain a login context, processing as first leg of request");
+            performAuthentication(inTransport, outTransport);
         } else {
-            completeAuthenticationRequest(request, response);
+            log.debug("Incoming request contains a login context, processing as second leg of request");
+            completeAuthenticationRequest(inTransport, outTransport);
         }
     }
 
@@ -148,52 +142,50 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
      * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
      * authenticating the user.
      * 
-     * @param request current request
-     * @param response current response
+     * @param inTransport inbound request transport
+     * @param outTransport outbound response transport
      * 
      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
      *             authentication manager
      */
-    protected void performAuthentication(ProfileRequest<ServletRequest> request,
-            ProfileResponse<ServletResponse> response) throws ProfileException {
-        HttpServletRequest httpRequest = (HttpServletRequest) request.getRawRequest();
+    protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
+            throws ProfileException {
+        HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
 
-        AuthnRequest authnRequest = null;
         try {
-            MessageDecoder<ServletRequest> decoder = decodeRequest(request);
-            SAMLSecurityPolicy securityPolicy = decoder.getSecurityPolicy();
-
-            String relyingParty = securityPolicy.getIssuer();
-            RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingParty);
-            if (rpConfig == null) {
-                log.error("No relying party configuration for " + relyingParty);
-                throw new ProfileException("No relying party configuration for " + relyingParty);
-            }
+            SSORequestContext requestContext = decodeRequest(inTransport, outTransport);
 
-            authnRequest = (AuthnRequest) decoder.getSAMLMessage();
+            String relyingPartyId = requestContext.getInboundMessageIssuer();
+            RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
+            ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(SSOConfiguration.PROFILE_ID);
+            if (ssoConfig == null) {
+                log.error("SAML 2 SSO profile is not configured for relying party "
+                        + requestContext.getInboundMessageIssuer());
+                throw new ProfileException("SAML 2 SSO profile is not configured for relying party "
+                        + requestContext.getInboundMessageIssuer());
+            }
 
-            Saml2LoginContext loginContext = new Saml2LoginContext(relyingParty, authnRequest);
+            log.debug("Creating login context and transferring control to authentication engine");
+            Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, requestContext.getRelayState(),
+                    requestContext.getInboundSAMLMessage());
             loginContext.setAuthenticationEngineURL(authenticationManagerPath);
-            loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
+            loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(servletRequest));
             if (loginContext.getRequestedAuthenticationMethods().size() == 0) {
                 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
             }
 
-            HttpSession httpSession = httpRequest.getSession();
-            httpSession.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
-            RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
-            dispatcher.forward(httpRequest, response.getRawResponse());
+            servletRequest.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
+            RequestDispatcher dispatcher = servletRequest.getRequestDispatcher(authenticationManagerPath);
+            dispatcher.forward(servletRequest, ((HttpServletResponseAdapter) outTransport).getWrappedResponse());
         } catch (MarshallingException e) {
             log.error("Unable to marshall authentication request context");
             throw new ProfileException("Unable to marshall authentication request context", e);
         } catch (IOException ex) {
-            log.error("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID() + " to AuthenticationManager", ex);
-            throw new ProfileException("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID()
-                    + " to AuthenticationManager", ex);
+            log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
+            throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
         } catch (ServletException ex) {
-            log.error("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID() + " to AuthenticationManager", ex);
-            throw new ProfileException("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID()
-                    + " to AuthenticationManager", ex);
+            log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
+            throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
         }
     }
 
@@ -201,39 +193,63 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
      * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
      * party after they've been authenticated.
      * 
-     * @param request current request
-     * @param response current response
+     * @param inTransport inbound message transport
+     * @param outTransport outbound message transport
      * 
      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
      */
-    protected void completeAuthenticationRequest(ProfileRequest<ServletRequest> request,
-            ProfileResponse<ServletResponse> response) throws ProfileException {
-
-        HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
-
-        Saml2LoginContext loginContext = (Saml2LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
-        httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
+    protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
+            throws ProfileException {
+        HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
 
-        SSORequestContext requestContext = buildRequestContext(loginContext, request, response);
+        Saml2LoginContext loginContext = (Saml2LoginContext) servletRequest
+                .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
+        SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
 
         checkSamlVersion(requestContext);
 
         Response samlResponse;
         try {
-            if (loginContext.getPrincipalName() == null) {
-                requestContext
-                        .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, null));
-                throw new ProfileException("User failed authentication");
+            if (loginContext.getAuthenticationFailure() != null) {
+                log.error("User authentication failed with the following error: {}", loginContext
+                        .getAuthenticationFailure().toString());
+
+                if (loginContext.getAuthenticationFailure() instanceof PassiveAuthenticationException) {
+                    requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.NO_PASSIVE_URI,
+                            null));
+                } else {
+                    requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
+                            null));
+                }
+                throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
+            }
+
+            if (requestContext.getSubjectNameIdentifier() != null) {
+                log
+                        .debug("Authentication request contained a subject with a name identifier, resolving principal from NameID");
+                resolvePrincipal(requestContext);
+                String requestedPrincipalName = requestContext.getPrincipalName();
+                if (!DatatypeHelper.safeEquals(loginContext.getPrincipalName(), requestedPrincipalName)) {
+                    log
+                            .error(
+                                    "Authentication request identified principal {} but authentication mechanism identified principal {}",
+                                    requestedPrincipalName, loginContext.getPrincipalName());
+                    requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
+                            null));
+                    throw new ProfileException("User failed authentication");
+                }
             }
 
-            AuthnStatement authnStatement = buildAuthnStatement(requestContext);
-            AttributeStatement attributeStatement = buildAttributeStatement(requestContext);
-            
+            resolveAttributes(requestContext);
+
             ArrayList<Statement> statements = new ArrayList<Statement>();
-            statements.add(authnStatement);
-            //TODO this isn't very effecient, support this flag better
-            if(requestContext.getProfileConfiguration().includeAttributeStatement()){
-                statements.add(attributeStatement);
+            statements.add(buildAuthnStatement(requestContext));
+            if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
+                AttributeStatement attributeStatement = buildAttributeStatement(requestContext);
+                if (attributeStatement != null) {
+                    requestContext.setRequestedAttributes(requestContext.getAttributes().keySet());
+                    statements.add(attributeStatement);
+                }
             }
 
             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
@@ -241,39 +257,61 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
             samlResponse = buildErrorResponse(requestContext);
         }
 
-        requestContext.setSamlResponse(samlResponse);
+        requestContext.setOutboundSAMLMessage(samlResponse);
+        requestContext.setOutboundSAMLMessageId(samlResponse.getID());
+        requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
         encodeResponse(requestContext);
         writeAuditLogEntry(requestContext);
     }
 
     /**
-     * Creates an appropriate message decoder, populates it, and decodes the incoming request.
+     * Decodes an incoming request and stores the information in a created request context.
      * 
-     * @param request current request
+     * @param inTransport inbound transport
+     * @param outTransport outbound transport
      * 
-     * @return message decoder containing the decoded message and other stateful information
+     * @return request context with decoded information
      * 
-     * @throws ProfileException thrown if the incomming message failed decoding
+     * @throws ProfileException thrown if the incoming message failed decoding
      */
-    protected MessageDecoder<ServletRequest> decodeRequest(ProfileRequest<ServletRequest> request)
+    protected SSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
             throws ProfileException {
-        MessageDecoder<ServletRequest> decoder = getMessageDecoderFactory().getMessageDecoder(decodingBinding);
-        if (decoder == null) {
-            log.error("No request decoder was registered for binding type: " + decodingBinding);
-            throw new ProfileException("No request decoder was registered for binding type: " + decodingBinding);
-        }
+        log.debug("Decoding message with decoder binding {}", getInboundBinding());
+        SSORequestContext requestContext = new SSORequestContext();
+        requestContext.setCommunicationProfileId(getProfileId());
+        
+        requestContext.setMetadataProvider(getMetadataProvider());
+        requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
+
+        requestContext.setCommunicationProfileId(SSOConfiguration.PROFILE_ID);
+        requestContext.setInboundMessageTransport(inTransport);
+        requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
+        requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
+
+        requestContext.setOutboundMessageTransport(outTransport);
+        requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
 
-        populateMessageDecoder(decoder);
-        decoder.setRequest(request.getRawRequest());
         try {
-            decoder.decode();
-            return decoder;
-        } catch (BindingException e) {
+            SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
+            requestContext.setMessageDecoder(decoder);
+            decoder.decode(requestContext);
+            log.debug("Decoded request");
+
+            if (!(requestContext.getInboundMessage() instanceof AuthnRequest)) {
+                log.error("Incomming message was not a AuthnRequest, it was a {}", requestContext.getInboundMessage()
+                        .getClass().getName());
+                requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, null,
+                        "Invalid SAML AuthnRequest message."));
+                throw new ProfileException("Invalid SAML AuthnRequest message.");
+            }
+
+            return requestContext;
+        } catch (MessageDecodingException e) {
             log.error("Error decoding authentication request message", e);
             throw new ProfileException("Error decoding authentication request message", e);
-        } catch (SecurityPolicyException e) {
-            log.error("Message did not meet security policy requirements", e);
-            throw new ProfileException("Message did not meet security policy requirements", e);
+        } catch (SecurityException e) {
+            log.error("Message did not meet security requirements", e);
+            throw new ProfileException("Message did not meet security requirements", e);
         }
     }
 
@@ -281,63 +319,96 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
      * Creates an authentication request context from the current environmental information.
      * 
      * @param loginContext current login context
-     * @param request current request
-     * @param response current response
+     * @param in inbound transport
+     * @param out outbount transport
      * 
      * @return created authentication request context
      * 
      * @throws ProfileException thrown if there is a problem creating the context
      */
-    protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext,
-            ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) throws ProfileException {
-        SSORequestContext requestContext = new SSORequestContext(request, response);
+    protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
+            HTTPOutTransport out) throws ProfileException {
+        SSORequestContext requestContext = new SSORequestContext();
+        requestContext.setCommunicationProfileId(getProfileId());
 
-        try {
-            requestContext.setMessageDecoder(getMessageDecoderFactory().getMessageDecoder(decodingBinding));
+        requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
 
-            requestContext.setLoginContext(loginContext);
+        requestContext.setLoginContext(loginContext);
 
-            String relyingPartyId = loginContext.getRelyingPartyId();
-            AuthnRequest authnRequest = loginContext.getAuthenticationRequest();
+        requestContext.setInboundMessageTransport(in);
+        requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
 
-            requestContext.setRelyingPartyId(relyingPartyId);
+        requestContext.setOutboundMessageTransport(out);
+        requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
 
-            requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(relyingPartyId));
+        requestContext.setMetadataProvider(getMetadataProvider());
 
-            requestContext.setRelyingPartyRoleMetadata(requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
-                    SAMLConstants.SAML20P_NS));
+        String relyingPartyId = loginContext.getRelyingPartyId();
+        requestContext.setPeerEntityId(relyingPartyId);
+        requestContext.setInboundMessageIssuer(relyingPartyId);
 
-            RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
-            requestContext.setRelyingPartyConfiguration(rpConfig);
+        populateRequestContext(requestContext);
 
-            requestContext.setAssertingPartyId(requestContext.getRelyingPartyConfiguration().getProviderId());
+        return requestContext;
+    }
 
-            requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(
-                    requestContext.getAssertingPartyId()));
+    /** {@inheritDoc} */
+    protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
+            throws ProfileException {
+        super.populateRelyingPartyInformation(requestContext);
+
+        EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
+        if (relyingPartyMetadata != null) {
+            requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
+            requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
+        }
+    }
 
-            requestContext.setAssertingPartyRoleMetadata(requestContext.getRelyingPartyMetadata().getIDPSSODescriptor(
-                    SAMLConstants.SAML20P_NS));
+    /** {@inheritDoc} */
+    protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
+            throws ProfileException {
+        super.populateAssertingPartyInformation(requestContext);
 
-            requestContext.setPrincipalName(loginContext.getPrincipalName());
+        EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
+        if (localEntityDescriptor != null) {
+            requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
+            requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
+                    .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
+        }
+    }
 
-            requestContext.setProfileConfiguration((SSOConfiguration) rpConfig
-                    .getProfileConfiguration(SSOConfiguration.PROFILE_ID));
+    /**
+     * Populates the request context with information from the inbound SAML message.
+     * 
+     * This method requires the the following request context properties to be populated: login context
+     * 
+     * This methods populates the following request context properties: inbound saml message, relay state, inbound saml
+     * message ID, subject name identifier
+     * 
+     * @param requestContext current request context
+     * 
+     * @throws ProfileException thrown if the inbound SAML message or subject identifier is null
+     */
+    protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
+        SSORequestContext ssoRequestContext = (SSORequestContext) requestContext;
+        try {
+            Saml2LoginContext loginContext = ssoRequestContext.getLoginContext();
+            requestContext.setRelayState(loginContext.getRelayState());
 
-            requestContext.setSamlRequest(authnRequest);
-            
-            selectEndpoint(requestContext);
+            AuthnRequest authnRequest = loginContext.getAuthenticationRequest();
+            requestContext.setInboundMessage(authnRequest);
+            requestContext.setInboundSAMLMessage(loginContext.getAuthenticationRequest());
+            requestContext.setInboundSAMLMessageId(loginContext.getAuthenticationRequest().getID());
 
-            return requestContext;
+            Subject authnSubject = authnRequest.getSubject();
+            if (authnSubject != null) {
+                requestContext.setSubjectNameIdentifier(authnSubject.getNameID());
+            }
         } catch (UnmarshallingException e) {
             log.error("Unable to unmarshall authentication request context");
-            requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
+            ssoRequestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
                     "Error recovering request state"));
             throw new ProfileException("Error recovering request state", e);
-        } catch (MetadataProviderException e) {
-            log.error("Unable to locate metadata for asserting or relying party");
-            requestContext
-                    .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error locating party metadata"));
-            throw new ProfileException("Error locating party metadata");
         }
     }
 
@@ -357,8 +428,10 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
         statement.setAuthnContext(authnContext);
         statement.setAuthnInstant(loginContext.getAuthenticationInstant());
 
-        // TODO
-        statement.setSessionIndex(null);
+        Session session = getUserSession(requestContext.getInboundMessageTransport());
+        if (session != null) {
+            statement.setSessionIndex(session.getSessionID());
+        }
 
         if (loginContext.getAuthenticationDuration() > 0) {
             statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
@@ -381,7 +454,7 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
         AuthnContext authnContext = authnContextBuilder.buildObject();
 
         Saml2LoginContext loginContext = requestContext.getLoginContext();
-        AuthnRequest authnRequest = requestContext.getSamlRequest();
+        AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
         RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
         if (requestedAuthnContext != null) {
             if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
@@ -418,89 +491,54 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
      * @return subject locality for the authentication statement
      */
     protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
+        HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
-
-        HttpServletRequest httpRequest = (HttpServletRequest) requestContext.getProfileRequest().getRawRequest();
-        subjectLocality.setAddress(httpRequest.getRemoteAddr());
-        subjectLocality.setDNSName(httpRequest.getRemoteHost());
+        subjectLocality.setAddress(transport.getPeerAddress());
 
         return subjectLocality;
     }
-    
+
     /**
      * Selects the appropriate endpoint for the relying party and stores it in the request context.
      * 
      * @param requestContext current request context
+     * 
+     * @return Endpoint selected from the information provided in the request context
      */
-    protected void selectEndpoint(SSORequestContext requestContext){
+    protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
+        AuthnRequest authnRequest = ((SSORequestContext) requestContext).getInboundSAMLMessage();
+
         AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
         endpointSelector.setMetadataProvider(getMetadataProvider());
-        endpointSelector.setRelyingParty(requestContext.getRelyingPartyMetadata());
-        endpointSelector.setRelyingPartyRole(requestContext.getRelyingPartyRoleMetadata());
-        endpointSelector.setSamlRequest(requestContext.getSamlRequest());
-        endpointSelector.getSupportedIssuerBindings().addAll(supportedOutgoingBindings);
-        requestContext.setRelyingPartyEndpoint(endpointSelector.selectEndpoint());
-    }
-
-    /**
-     * Encodes the request's SAML response and writes it to the servlet response.
-     * 
-     * @param requestContext current request context
-     * 
-     * @throws ProfileException thrown if no message encoder is registered for this profiles binding
-     */
-    protected void encodeResponse(SSORequestContext requestContext) throws ProfileException {
-        if (log.isDebugEnabled()) {
-            log.debug("Encoding response to SAML request " + requestContext.getSamlRequest().getID()
-                    + " from relying party " + requestContext.getRelyingPartyId());
-        }
-
-        Endpoint relyingPartyEndpoint = requestContext.getRelyingPartyEndpoint();
-        MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(
-                relyingPartyEndpoint.getBinding());
-        if (encoder == null) {
-            log.error("No response encoder was registered for binding type: " + relyingPartyEndpoint.getBinding());
-            throw new ProfileException("No response encoder was registered for binding type: "
-                    + relyingPartyEndpoint.getBinding());
+        endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
+        endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
+        endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
+        endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
+
+        Endpoint endpoint = endpointSelector.selectEndpoint();
+        if (endpoint == null && authnRequest.getAssertionConsumerServiceURL() != null) {
+            endpoint = endpointBuilder.buildObject();
+            endpoint.setLocation(authnRequest.getAssertionConsumerServiceURL());
+            if (authnRequest.getProtocolBinding() != null) {
+                endpoint.setBinding(authnRequest.getProtocolBinding());
+            } else {
+                endpoint.setBinding(getSupportedOutboundBindings().get(0));
+            }
+            log.warn("No endpoint available for relying party {}. Generating endpoint with ACS url {} and binding {}",
+                    new Object[] { requestContext.getPeerEntityId(), endpoint.getLocation(), endpoint.getBinding() });
         }
 
-        super.populateMessageEncoder(encoder);
-        encoder.setIssuer(requestContext.getAssertingPartyId());
-        encoder.setRelayState(requestContext.getMessageDecoder().getRelayState());
-        encoder.setRelyingParty(requestContext.getRelyingPartyMetadata());
-        encoder.setRelyingPartyEndpoint(relyingPartyEndpoint);
-        encoder.setRelyingPartyRole(requestContext.getRelyingPartyRoleMetadata());
-        ProfileResponse<ServletResponse> profileResponse = requestContext.getProfileResponse();
-        encoder.setResponse(profileResponse.getRawResponse());
-        encoder.setSamlMessage(requestContext.getSamlResponse());
-        requestContext.setMessageEncoder(encoder);
-
-        try {
-            encoder.encode();
-        } catch (BindingException e) {
-            throw new ProfileException("Unable to encode response to relying party: "
-                    + requestContext.getRelyingPartyId(), e);
-        }
+        return endpoint;
     }
 
     /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
-    protected class SSORequestContext extends SAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
+    protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
 
         /** Current login context. */
         private Saml2LoginContext loginContext;
 
         /**
-         * Constructor.
-         * 
-         * @param request current profile request
-         * @param response current profile response
-         */
-        public SSORequestContext(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) {
-            super(request, response);
-        }
-
-        /**
          * Gets the current login context.
          * 
          * @return current login context