Set communication profile before decoding
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml1 / ShibbolethSSOProfileHandler.java
index c2758e5..da1ab1f 100644 (file)
 package edu.internet2.middleware.shibboleth.idp.profile.saml1;
 
 import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.net.URLDecoder;
 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.HttpServletResponse;
-import javax.servlet.http.HttpSession;
 
-import org.apache.log4j.Logger;
 import org.opensaml.common.SAMLObjectBuilder;
-import org.opensaml.common.binding.BasicEndpointSelector;
-import org.opensaml.common.binding.BindingException;
-import org.opensaml.common.binding.encoding.MessageEncoder;
+import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
+import org.opensaml.common.xml.SAMLConstants;
+import org.opensaml.saml1.core.AttributeStatement;
 import org.opensaml.saml1.core.AuthenticationStatement;
 import org.opensaml.saml1.core.Request;
 import org.opensaml.saml1.core.Response;
@@ -44,14 +37,23 @@ import org.opensaml.saml1.core.Subject;
 import org.opensaml.saml1.core.SubjectLocality;
 import org.opensaml.saml2.metadata.AssertionConsumerService;
 import org.opensaml.saml2.metadata.Endpoint;
-import org.opensaml.saml2.metadata.RoleDescriptor;
-import org.opensaml.saml2.metadata.provider.MetadataProviderException;
+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.security.SecurityException;
 import org.opensaml.xml.util.DatatypeHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import edu.internet2.middleware.shibboleth.common.ShibbolethConstants;
 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.saml1.ShibbolethSSOConfiguration;
 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
@@ -62,7 +64,7 @@ import edu.internet2.middleware.shibboleth.idp.authn.ShibbolethSSOLoginContext;
 public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
 
     /** Class logger. */
-    private final Logger log = Logger.getLogger(ShibbolethSSOProfileHandler.class);
+    private final Logger log = LoggerFactory.getLogger(ShibbolethSSOProfileHandler.class);
 
     /** Builder of AuthenticationStatement objects. */
     private SAMLObjectBuilder<AuthenticationStatement> authnStatementBuilder;
@@ -70,66 +72,54 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
     /** 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 1 bindings supported for outgoing message encoding. */
-    private ArrayList<String> supportedOutgoingBindings;
 
     /**
      * Constructor.
      * 
      * @param authnManagerPath path to the authentication manager servlet
-     * @param outgoingBindings URIs of SAML 1 bindings supported for outgoing message encoding
      * 
      * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
      *             null or empty
      */
-    public ShibbolethSSOProfileHandler(String authnManagerPath, List<String> outgoingBindings) {
+    public ShibbolethSSOProfileHandler(String authnManagerPath) {
         if (DatatypeHelper.isEmpty(authnManagerPath)) {
             throw new IllegalArgumentException("Authentication manager path 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);
 
         authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
                 AuthenticationStatement.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:shibboleth:request:sso";
+        return ShibbolethSSOConfiguration.PROFILE_ID;
     }
 
     /** {@inheritDoc} */
-    public void processRequest(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
-            throws ProfileException {
+    public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
+        log.debug("Processing incoming request");
 
-        if (response.getRawResponse().isCommitted()) {
-            log.error("HTTP Response already committed");
-        }
+        HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
+        LoginContext loginContext = (LoginContext) httpRequest.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
 
-        if (log.isDebugEnabled()) {
-            log.debug("Processing incomming request");
-        }
-        HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
-        if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
-            if (log.isDebugEnabled()) {
-                log.debug("User session does not contain a login context, processing as first leg of request");
-            }
-            performAuthentication(request, response);
+        if (loginContext == null) {
+            log.debug("Incoming request does not contain a login context, processing as first leg of request");
+            performAuthentication(inTransport, outTransport);
         } else {
-            if (log.isDebugEnabled()) {
-                log.debug("User session contains a login context, processing as second leg of request");
-            }
-            completeAuthenticationRequest(request, response);
+            log.debug("Incoming request contains a login context, processing as second leg of request");
+            completeAuthenticationRequest(inTransport, outTransport);
         }
     }
 
@@ -137,27 +127,31 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
      * Creates a {@link LoginContext} 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 message transport
+     * @param outTransport outbound message 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 {
+    protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
+            throws ProfileException {
 
-        HttpServletRequest httpRequest = (HttpServletRequest) request.getRawRequest();
-        HttpServletResponse httpResponse = (HttpServletResponse) response.getRawResponse();
-        HttpSession httpSession = httpRequest.getSession(true);
+        HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
+        HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
+
+        ShibbolethSSORequestContext requestContext = decodeRequest(inTransport, outTransport);
+        ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
 
-        LoginContext loginContext = buildLoginContext(httpRequest);
-        if (getRelyingPartyConfiguration(loginContext.getRelyingPartyId()) == null) {
+        RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(loginContext.getRelyingPartyId());
+        ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
+        if (ssoConfig == null) {
             log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
             throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
                     + loginContext.getRelyingPartyId());
         }
+        loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
 
-        httpSession.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
+        httpRequest.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
 
         try {
             RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
@@ -173,37 +167,95 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
     }
 
     /**
+     * Decodes an incoming request and populates a created request context with the resultant information.
+     * 
+     * @param inTransport inbound message transport
+     * @param outTransport outbound message transport
+     * 
+     * @return the created request context
+     * 
+     * @throws ProfileException throw if there is a problem decoding the request
+     */
+    protected ShibbolethSSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
+            throws ProfileException {
+        log.debug("Decoding message with decoder binding {}", getInboundBinding());
+
+        HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
+
+        ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
+        requestContext.setCommunicationProfileId(getProfileId());
+        
+        requestContext.setMetadataProvider(getMetadataProvider());
+        requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
+
+        requestContext.setCommunicationProfileId(ShibbolethSSOConfiguration.PROFILE_ID);
+        requestContext.setInboundMessageTransport(inTransport);
+        requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
+        requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
+
+        requestContext.setOutboundMessageTransport(outTransport);
+        requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
+
+        SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
+        requestContext.setMessageDecoder(decoder);
+        try {
+            decoder.decode(requestContext);
+        } catch (MessageDecodingException e) {
+            log.error("Error decoding Shibboleth SSO request", e);
+            throw new ProfileException("Error decoding Shibboleth SSO request", e);
+        } catch (SecurityException e) {
+            log.error("Shibboleth SSO request does not meet security requirements", e);
+            throw new ProfileException("Shibboleth SSO request does not meet security requirements", e);
+        }
+
+        ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
+        loginContext.setRelyingParty(requestContext.getInboundMessageIssuer());
+        loginContext.setSpAssertionConsumerService(requestContext.getSpAssertionConsumerService());
+        loginContext.setSpTarget(requestContext.getRelayState());
+        loginContext.setAuthenticationEngineURL(authenticationManagerPath);
+        loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
+        requestContext.setLoginContext(loginContext);
+
+        return requestContext;
+    }
+
+    /**
      * Creates a response to the Shibboleth SSO 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);
-
-        ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
+    protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
+            throws ProfileException {
+        HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
+        ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpRequest
                 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
-        httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
 
-        ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, request, response);
+        ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
 
         Response samlResponse;
         try {
-            if (loginContext.getPrincipalName() == null) {
+            if (loginContext.getAuthenticationFailure() != null) {
+                log.error("User authentication failed with the following error: {}", loginContext
+                        .getAuthenticationFailure().toString());
                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
-                throw new ProfileException("User failed authentication");
+                throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
             }
-            
+
             resolveAttributes(requestContext);
-            
+
             ArrayList<Statement> statements = new ArrayList<Statement>();
             statements.add(buildAuthenticationStatement(requestContext));
             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
-                statements.add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer"));
+                AttributeStatement attributeStatement = buildAttributeStatement(requestContext,
+                        "urn:oasis:names:tc:SAML:1.0:cm:bearer");
+                if (attributeStatement != null) {
+                    requestContext.setRequestedAttributes(requestContext.getAttributes().keySet());
+                    statements.add(attributeStatement);
+                }
             }
 
             samlResponse = buildResponse(requestContext, statements);
@@ -211,163 +263,110 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
             samlResponse = buildErrorResponse(requestContext);
         }
 
-        requestContext.setSamlResponse(samlResponse);
+        requestContext.setOutboundSAMLMessage(samlResponse);
+        requestContext.setOutboundSAMLMessageId(samlResponse.getID());
+        requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
         encodeResponse(requestContext);
         writeAuditLogEntry(requestContext);
     }
 
     /**
-     * Creates a login context from the incoming HTTP request.
-     * 
-     * @param request current HTTP request
-     * 
-     * @return the constructed login context
-     * 
-     * @throws ProfileException thrown if the incomming request did not contain a providerId, shire, and target
-     *             parameter
-     */
-    protected ShibbolethSSOLoginContext buildLoginContext(HttpServletRequest request) throws ProfileException {
-        ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
-
-        try {
-            String providerId = DatatypeHelper.safeTrimOrNullString(request.getParameter("providerId"));
-            if (providerId == null) {
-                log.error("No providerId parameter in Shibboleth SSO request");
-                throw new ProfileException("No providerId parameter in Shibboleth SSO request");
-            }
-            loginContext.setRelyingParty(URLDecoder.decode(providerId, "UTF-8"));
-
-            RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(providerId);
-            if (rpConfig == null) {
-                log.error("No relying party configuration available for " + providerId);
-                throw new ProfileException("No relying party configuration available for " + providerId);
-            }
-            loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
-
-            String acs = DatatypeHelper.safeTrimOrNullString(request.getParameter("shire"));
-            if (acs == null) {
-                log.error("No shire parameter in Shibboleth SSO request");
-                throw new ProfileException("No shire parameter in Shibboleth SSO request");
-            }
-            loginContext.setSpAssertionConsumerService(URLDecoder.decode(acs, "UTF-8"));
-
-            String target = DatatypeHelper.safeTrimOrNullString(request.getParameter("target"));
-            if (target == null) {
-                log.error("No target parameter in Shibboleth SSO request");
-                throw new ProfileException("No target parameter in Shibboleth SSO request");
-            }
-            loginContext.setSpTarget(URLDecoder.decode(target, "UTF-8"));
-        } catch (UnsupportedEncodingException e) {
-            // UTF-8 encoding required to be supported by all JVMs.
-        }
-
-        loginContext.setAuthenticationEngineURL(authenticationManagerPath);
-        loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(request));
-        return loginContext;
-    }
-
-    /**
      * 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 asserting and relying party metadata can not be located
+     * @throws ProfileException thrown if there is a problem creating the context
      */
     protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
-            ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) throws ProfileException {
-        ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext(request, response);
+            HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
+        ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
+        requestContext.setCommunicationProfileId(getProfileId());
 
-        requestContext.setRelayState(loginContext.getSpTarget());
-        
-        requestContext.setLoginContext(loginContext);
+        requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
 
-        requestContext.setPrincipalName(loginContext.getPrincipalName());
+        requestContext.setLoginContext(loginContext);
+        requestContext.setRelayState(loginContext.getSpTarget());
 
-        requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
+        requestContext.setInboundMessageTransport(in);
+        requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
 
-        String relyingPartyId = loginContext.getRelyingPartyId();
+        requestContext.setOutboundMessageTransport(out);
+        requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
 
-        requestContext.setRelyingPartyId(relyingPartyId);
+        requestContext.setMetadataProvider(getMetadataProvider());
 
-        populateRelyingPartyData(requestContext);
+        String relyingPartyId = loginContext.getRelyingPartyId();
+        requestContext.setPeerEntityId(relyingPartyId);
+        requestContext.setInboundMessageIssuer(relyingPartyId);
 
-        populateAssertingPartyData(requestContext);
+        populateRequestContext(requestContext);
 
         return requestContext;
     }
 
-    /**
-     * Populates the relying party entity and role metadata and relying party configuration data.
-     * 
-     * @param requestContext current request context with relying party ID populated
-     * 
-     * @throws ProfileException thrown if metadata can not be located for the relying party
-     */
-    protected void populateRelyingPartyData(ShibbolethSSORequestContext requestContext) throws ProfileException {
-        try {
-            requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(
-                    requestContext.getRelyingPartyId()));
-
-            RoleDescriptor relyingPartyRole = requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
-                    ShibbolethConstants.SAML11P_NS);
-
-            if (relyingPartyRole == null) {
-                relyingPartyRole = requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
-                        ShibbolethConstants.SAML10P_NS);
-                if (relyingPartyRole == null) {
-                    throw new MetadataProviderException("Unable to locate SPSSO role descriptor for entity "
-                            + requestContext.getRelyingPartyId());
-                }
-            }
-            requestContext.setRelyingPartyRoleMetadata(relyingPartyRole);
+    /** {@inheritDoc} */
+    protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
+            throws ProfileException {
+        super.populateRelyingPartyInformation(requestContext);
 
-            RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(requestContext.getRelyingPartyId());
-            requestContext.setRelyingPartyConfiguration(rpConfig);
+        EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
+        if (relyingPartyMetadata != null) {
+            requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
+            requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML11P_NS));
+        }
+    }
 
-            requestContext.setProfileConfiguration((ShibbolethSSOConfiguration) rpConfig
-                    .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID));
+    /** {@inheritDoc} */
+    protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
+            throws ProfileException {
+        super.populateAssertingPartyInformation(requestContext);
 
-        } catch (MetadataProviderException e) {
-            log.error("Unable to locate metadata for relying party " + requestContext.getRelyingPartyId());
-            requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
-                    "Unable to locate metadata for relying party " + requestContext.getRelyingPartyId()));
-            throw new ProfileException("Unable to locate metadata for relying party "
-                    + requestContext.getRelyingPartyId());
+        EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
+        if (localEntityDescriptor != null) {
+            requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
+            requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
+                    .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
         }
     }
 
+    /** {@inheritDoc} */
+    protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
+        // nothing to do here
+    }
+
     /**
-     * Populates the asserting party entity and role metadata.
+     * Selects the appropriate endpoint for the relying party and stores it in the request context.
      * 
-     * @param requestContext current request context with relying party configuration populated
+     * @param requestContext current request context
      * 
-     * @throws ProfileException thrown if metadata can not be located for the asserting party
+     * @return Endpoint selected from the information provided in the request context
      */
-    protected void populateAssertingPartyData(ShibbolethSSORequestContext requestContext) throws ProfileException {
-        String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
-
-        try {
-            requestContext.setAssertingPartyId(assertingPartyId);
-
-            requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(assertingPartyId));
+    protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
+        ShibbolethSSOLoginContext loginContext = ((ShibbolethSSORequestContext) requestContext).getLoginContext();
 
-            RoleDescriptor assertingPartyRole = requestContext.getAssertingPartyMetadata().getIDPSSODescriptor(
-                    ShibbolethConstants.SHIB_SSO_PROFILE_URI);
-            if (assertingPartyRole == null) {
-                throw new MetadataProviderException("Unable to locate IDPSSO role descriptor for entity "
-                        + assertingPartyId);
-            }
-            requestContext.setAssertingPartyRoleMetadata(assertingPartyRole);
-        } catch (MetadataProviderException e) {
-            log.error("Unable to locate metadata for asserting party " + assertingPartyId);
-            requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
-                    "Unable to locate metadata for relying party " + assertingPartyId));
-            throw new ProfileException("Unable to locate metadata for relying party " + assertingPartyId);
+        ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
+        endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
+        endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
+        endpointSelector.setMetadataProvider(getMetadataProvider());
+        endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
+        endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
+        endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
+        endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
+
+        Endpoint endpoint = endpointSelector.selectEndpoint();
+        if (endpoint == null && loginContext.getSpAssertionConsumerService() != null) {
+            endpoint = endpointBuilder.buildObject();
+            endpoint.setLocation(loginContext.getSpAssertionConsumerService());
+            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() });
         }
+
+        return endpoint;
     }
 
     /**
@@ -405,80 +404,23 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
     protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
 
-        HttpServletRequest httpRequest = (HttpServletRequest) requestContext.getProfileRequest().getRawRequest();
-        subjectLocality.setIPAddress(httpRequest.getRemoteAddr());
-        subjectLocality.setDNSAddress(httpRequest.getRemoteHost());
+        HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
+        subjectLocality.setIPAddress(inTransport.getPeerAddress());
 
         return subjectLocality;
     }
 
-    /**
-     * 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(ShibbolethSSORequestContext requestContext) throws ProfileException {
-        if (log.isDebugEnabled()) {
-            log.debug("Encoding response to SAML request from relying party " + requestContext.getRelyingPartyId());
-        }
-
-        Endpoint relyingPartyEndpoint;
-
-        BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
-        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);
-        relyingPartyEndpoint = endpointSelector.selectEndpoint();
-
-        if (relyingPartyEndpoint == null) {
-            log.error("Unable to determine endpoint, from metadata, for relying party "
-                    + requestContext.getRelyingPartyId() + " acting in SPSSO role");
-            throw new ProfileException("Unable to determine endpoint, from metadata, for relying party "
-                    + requestContext.getRelyingPartyId() + " acting in SPSSO role");
-        }
-
-        MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(
-                relyingPartyEndpoint.getBinding());
-        encoder.setRelyingPartyEndpoint(relyingPartyEndpoint);
-        super.populateMessageEncoder(encoder);
-        encoder.setRelayState(requestContext.getRelayState());
-        ProfileResponse<ServletResponse> profileResponse = requestContext.getProfileResponse();
-        encoder.setResponse(profileResponse.getRawResponse());
-        encoder.setSamlMessage(requestContext.getSamlResponse());
-        requestContext.setMessageEncoder(encoder.getBindingURI());
-
-        try {
-            encoder.encode();
-        } catch (BindingException e) {
-            throw new ProfileException("Unable to encode response to relying party: "
-                    + requestContext.getRelyingPartyId(), e);
-        }
-    }
-
     /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
-    protected class ShibbolethSSORequestContext extends
-            SAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
+    public class ShibbolethSSORequestContext extends
+            BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
+
+        /** SP-provide assertion consumer service URL. */
+        private String spAssertionConsumerService;
 
         /** Current login context. */
         private ShibbolethSSOLoginContext loginContext;
 
         /**
-         * Constructor.
-         * 
-         * @param request current profile request
-         * @param response current profile response
-         */
-        public ShibbolethSSORequestContext(ProfileRequest<ServletRequest> request,
-                ProfileResponse<ServletResponse> response) {
-            super(request, response);
-        }
-
-        /**
          * Gets the current login context.
          * 
          * @return current login context
@@ -495,5 +437,23 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
         public void setLoginContext(ShibbolethSSOLoginContext context) {
             loginContext = context;
         }
+
+        /**
+         * Gets the SP-provided assertion consumer service URL.
+         * 
+         * @return SP-provided assertion consumer service URL
+         */
+        public String getSpAssertionConsumerService() {
+            return spAssertionConsumerService;
+        }
+
+        /**
+         * Sets the SP-provided assertion consumer service URL.
+         * 
+         * @param acs SP-provided assertion consumer service URL
+         */
+        public void setSpAssertionConsumerService(String acs) {
+            spAssertionConsumerService = acs;
+        }
     }
 }
\ No newline at end of file