rework saml2 authnreq handler to use a requestcontext object. will make future extens...
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / AbstractAuthenticationRequest.java
index 01f6d3c..de46cd2 100644 (file)
@@ -26,24 +26,25 @@ 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.joda.time.DateTime;
 import org.opensaml.Configuration;
 import org.opensaml.common.SAMLObjectBuilder;
-import org.opensaml.common.binding.ArtifactMap;
-import org.opensaml.common.binding.SAMLArtifactFactory;
+import org.opensaml.common.binding.BindingException;
+import org.opensaml.common.binding.encoding.MessageEncoder;
 import org.opensaml.saml2.core.Assertion;
 import org.opensaml.saml2.core.AuthnContext;
 import org.opensaml.saml2.core.AuthnContextClassRef;
 import org.opensaml.saml2.core.AuthnContextDeclRef;
 import org.opensaml.saml2.core.AuthnRequest;
 import org.opensaml.saml2.core.AuthnStatement;
-import org.opensaml.saml2.core.Condition;
-import org.opensaml.saml2.core.Conditions;
 import org.opensaml.saml2.core.GetComplete;
 import org.opensaml.saml2.core.IDPEntry;
 import org.opensaml.saml2.core.IDPList;
@@ -56,10 +57,11 @@ import org.opensaml.saml2.core.StatusCode;
 import org.opensaml.saml2.core.Subject;
 import org.opensaml.saml2.core.SubjectConfirmation;
 import org.opensaml.saml2.metadata.AssertionConsumerService;
+import org.opensaml.saml2.metadata.Endpoint;
+import org.opensaml.saml2.metadata.RoleDescriptor;
 import org.opensaml.saml2.metadata.SPSSODescriptor;
 import org.opensaml.saml2.metadata.provider.MetadataProvider;
 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
-import org.opensaml.xml.ConfigurationException;
 import org.opensaml.xml.io.Unmarshaller;
 import org.opensaml.xml.io.UnmarshallingException;
 import org.opensaml.xml.parse.BasicParserPool;
@@ -68,45 +70,265 @@ import org.opensaml.xml.parse.XMLParserException;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
+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.ProfileConfiguration;
 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
-import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfigurationManager;
-import edu.internet2.middleware.shibboleth.common.relyingparty.saml2.AbstractSAML2ProfileConfiguration;
-import edu.internet2.middleware.shibboleth.common.relyingparty.saml2.SSOConfiguration;
+import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AbstractSAML2ProfileConfiguration;
+import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
 import edu.internet2.middleware.shibboleth.idp.authn.AuthenticationManager;
 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
 
-
 /**
  * Abstract SAML 2.0 Authentication Request profile handler.
  */
 public abstract class AbstractAuthenticationRequest extends AbstractSAML2ProfileHandler {
     
-    /** Class logger. */
-    private static final Logger log = Logger.getLogger(AbstractAuthenticationRequest.class);
-    
-    /** Key in an HttpSession for the AssertionConsumerService object. */
-    protected static final String ACS_SESSION_KEY = "AssertionConsumerService";
     
-    /** Key in an HttpSession for the RelyingParty. */
-    protected static final String RPCONFIG_SESSION_KEY = "RelyingPartyConfiguration";
-    
-    /** Key in an HttpSession for the SSOConfiguration. */
-    protected static final String SSOCONFIG_SESSION_KEY = "SSOConfiguration";
-    
-    /** Key in an HttpSession for the SPSSODescriptor. */
-    protected static final String SPSSODESC_SESSION_KEY = "SPSSODescriptor";
+    /**
+     * Represents the internal state of a SAML 2.0 Authentiation Request while it's being processed by the IdP.
+     */
+    protected class AuthenticationRequestContext {
+        
+        /** The ProfileRequest. */
+        protected ProfileRequest<ServletRequest> profileRequest;
+        
+        /** The ProfileResponse. */
+        protected ProfileResponse<ServletResponse> profileResponse;
+        
+        /** The HttpServletRequest. */
+        protected HttpServletRequest servletRequest;
+        
+        /** The HttpServletResponse. */
+        protected HttpServletResponse servletResponse;
+        
+        /** The SAML 2.0 AuthnRequest. */
+        protected AuthnRequest authnRequest;
+        
+        /** The issuer. */
+        protected String issuer;
+        
+        /** The Subject. */
+        protected Subject subject;
+        
+        /** The Response. */
+        protected Response response;
+        
+        /** The IdP's LoginContext. */
+        protected LoginContext loginContext;
+        
+        /** The RelyingPartyConfiguration. */
+        protected RelyingPartyConfiguration rpConfig;
+        
+        /** The SSOConfiguration. */
+        protected SSOConfiguration ssoConfig;
+        
+        /** The SPSSOConfiguration. */
+        protected SPSSODescriptor spDescriptor;
+        
+        /** The AssertionConsumerService endpoint. */
+        protected AssertionConsumerService assertionConsumerService;
+        
+        public AuthenticationRequestContext() {
+        }
+        
+        public ProfileRequest<ServletRequest> getProfileRequest() {
+            return profileRequest;
+        }
+        
+        public void setProfileRequest(ProfileRequest<ServletRequest> profileRequest) {
+            this.profileRequest = profileRequest;
+            this.servletRequest = (HttpServletRequest) profileRequest.getRawRequest();
+        }
+        
+        public ProfileResponse<ServletResponse> getProfileResponse() {
+            return profileResponse;
+        }
+        
+        public void setProfileResponse(ProfileResponse<ServletResponse> profileResponse) {
+            this.profileResponse = profileResponse;
+            this.servletResponse = (HttpServletResponse) profileResponse.getRawResponse();
+        }
+        
+        public HttpServletRequest getServletRequest() {
+            return servletRequest;
+        }
+        
+        public void setServletRequest(HttpServletRequest servletRequest) {
+            this.servletRequest = servletRequest;
+        }
+        
+        public HttpServletResponse getServletResponse() {
+            return servletResponse;
+        }
+        
+        public void setServletResponse(HttpServletResponse servletResponse) {
+            this.servletResponse = servletResponse;
+        }
+        
+        public HttpSession getHttpSession() {
+            
+            if (getServletRequest() != null) {
+                return getServletRequest().getSession();
+            } else {
+                return null;
+            }
+        }
+        
+        public AuthnRequest getAuthnRequest() {
+            return authnRequest;
+        }
+        
+        public void setAuthnRequest(AuthnRequest authnRequest) {
+            this.authnRequest = authnRequest;
+        }
+        
+        public String getIssuer() {
+            return issuer;
+        }
+        
+        public void setIssuer(String issuer) {
+            this.issuer = issuer;
+        }
+        
+        public Subject getSubject() {
+            return subject;
+        }
+        
+        public void setSubject(Subject subject) {
+            this.subject = subject;
+        }
+        
+        public LoginContext getLoginContext() {
+            return loginContext;
+        }
+        
+        public void setLoginContext(LoginContext loginContext) {
+            this.loginContext = loginContext;
+        }
+        
+        public RelyingPartyConfiguration getRpConfig() {
+            return rpConfig;
+        }
+        
+        public void setRpConfig(RelyingPartyConfiguration rpConfig) {
+            this.rpConfig = rpConfig;
+        }
+        
+        public SSOConfiguration getSsoConfig() {
+            return ssoConfig;
+        }
+        
+        public void setSsoConfig(SSOConfiguration ssoConfig) {
+            this.ssoConfig = ssoConfig;
+        }
+        
+        public SPSSODescriptor getSpDescriptor() {
+            return spDescriptor;
+        }
+        
+        public void setSpDescriptor(SPSSODescriptor spDescriptor) {
+            this.spDescriptor = spDescriptor;
+        }
+        
+        public Response getResponse() {
+            return response;
+        }
+        
+        public void setResponse(Response response) {
+            this.response = response;
+        }
+        
+        public AssertionConsumerService getAssertionConsumerService() {
+            return assertionConsumerService;
+        }
+        
+        public void setAssertionConsumerService(AssertionConsumerService assertionConsumerService) {
+            this.assertionConsumerService = assertionConsumerService;
+        }
+        
+        public boolean equals(Object obj) {
+            if (obj == null) {
+                return false;
+            }
+            
+            if (getClass() != obj.getClass()) {
+                return false;
+            }
+            
+            final edu.internet2.middleware.shibboleth.idp.profile.saml2.AbstractAuthenticationRequest.AuthenticationRequestContext other = (edu.internet2.middleware.shibboleth.idp.profile.saml2.AbstractAuthenticationRequest.AuthenticationRequestContext) obj;
+            
+            if (this.profileRequest != other.profileRequest && (this.profileRequest == null || !this.profileRequest.equals(other.profileRequest))) {
+                return false;
+            }
+            
+            if (this.profileResponse != other.profileResponse && (this.profileResponse == null || !this.profileResponse.equals(other.profileResponse))) {
+                return false;
+            }
+            
+            if (this.servletRequest != other.servletRequest && (this.servletRequest == null || !this.servletRequest.equals(other.servletRequest))) {
+                return false;
+            }
+            
+            if (this.servletResponse != other.servletResponse && (this.servletResponse == null || !this.servletResponse.equals(other.servletResponse))) {
+                return false;
+            }
+            
+            if (this.authnRequest != other.authnRequest && (this.authnRequest == null || !this.authnRequest.equals(other.authnRequest))) {
+                return false;
+            }
+            
+            if (this.issuer != other.issuer && (this.issuer == null || !this.issuer.equals(other.issuer))) {
+                return false;
+            }
+            
+            if (this.subject != other.subject && (this.subject == null || !this.subject.equals(other.subject))) {
+                return false;
+            }
+            
+            if (this.response != other.response && (this.response == null || !this.response.equals(other.response))) {
+                return false;
+            }
+            
+            if (this.loginContext != other.loginContext && (this.loginContext == null || !this.loginContext.equals(other.loginContext))) {
+                return false;
+            }
+            
+            if (this.rpConfig != other.rpConfig && (this.rpConfig == null || !this.rpConfig.equals(other.rpConfig))) {
+                return false;
+            }
+            
+            if (this.ssoConfig != other.ssoConfig && (this.ssoConfig == null || !this.ssoConfig.equals(other.ssoConfig))) {
+                return false;
+            }
+            
+            if (this.spDescriptor != other.spDescriptor && (this.spDescriptor == null || !this.spDescriptor.equals(other.spDescriptor))) {
+                return false;
+            }
+            
+            if (this.assertionConsumerService != other.assertionConsumerService && (this.assertionConsumerService == null || !this.assertionConsumerService.equals(other.assertionConsumerService))) {
+                return false;
+            }
+            
+            return true;
+        }
+        
+        public int hashCode() {
+            int hash = 7;
+            return hash;
+        }
+        
+        
+    }
     
-    /** Key in an HttpSession for the AuthnRequest. */
-    protected static final String AUTHNREQUEST_SESSION_KEY = "AuthnRequest";
     
-    /** Key in an HttpSession for the Issuer. */
-    protected static final String ISSUER_SESSION_KEY = "Issuer";
+    /** Class logger. */
+    private static final Logger log = Logger.getLogger(AbstractAuthenticationRequest.class);
     
-    /** Backing store for artifacts. */
-    protected ArtifactMap artifactMap;
+    /** HttpSession key for the AuthenticationRequestContext. */
+    protected static final String REQUEST_CONTEXT_SESSION_KEY = "edu.internet2.middleware.shibboleth.idp.profile.saml2.AuthenticationRequestContext";
     
     /** The path to the IdP's AuthenticationManager servlet */
     protected String authnMgrURL;
@@ -114,9 +336,6 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
     /** AuthenticationManager to be used */
     protected AuthenticationManager authnMgr;
     
-    /** ArtifactFactory used to make artifacts. */
-    protected SAMLArtifactFactory artifactFactory;
-    
     /** A pool of XML parsers. */
     protected ParserPool parserPool;
     
@@ -138,7 +357,6 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
     public AbstractAuthenticationRequest() {
         
         parserPool = new BasicParserPool();
-        artifactFactory = new SAMLArtifactFactory();
         authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) getBuilderFactory().getBuilder(AuthnStatement.DEFAULT_ELEMENT_NAME);
         authnContextBuilder = (SAMLObjectBuilder<AuthnContext>) getBuilderFactory().getBuilder(AuthnContext.DEFAULT_ELEMENT_NAME);
         authnContextDeclRefBuilder = (SAMLObjectBuilder<AuthnContextDeclRef>) getBuilderFactory().getBuilder(AuthnContextDeclRef.DEFAULT_ELEMENT_NAME);
@@ -156,16 +374,6 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
     }
     
     /**
-     * Set the ArtifactMap.
-     *
-     * @param artifactMap
-     *            The IdP's ArtifactMap.
-     */
-    public void setArtifactMap(ArtifactMap artifactMap) {
-        this.artifactMap = artifactMap;
-    }
-    
-    /**
      * Evaluate a SAML 2 AuthenticationRequest message.
      *
      * @param authnRequest
@@ -181,31 +389,22 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
      * @param spDescriptor
      *            The SPSSODescriptor for the request.
      *
-     * @return A Response containing a failure message or a AuthenticationStmt.
-     *
-     * @throws ServletException
+     * @throws ProfileException
      *             On Error.
      */
-    protected Response evaluateRequest(final AuthnRequest authnRequest,
-            final Issuer issuer, final HttpSession session,
-            final RelyingPartyConfiguration relyingParty,
-            final SSOConfiguration ssoConfig, final SPSSODescriptor spDescriptor)
-            throws ServletException {
+    protected void evaluateRequest(final AuthenticationRequestContext requestContext) throws ProfileException {
         
         Response samlResponse;
         
-        try {
-            // check if the authentication was successful.
-            Saml2LoginContext loginCtx = getLoginContext(session);
-            if (!loginCtx.getAuthenticationOK()) {
-                // if authentication failed, send the appropriate SAML error message.
-                String failureMessage = loginCtx.getAuthenticationFailureMessage();
-                Status failureStatus = buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, failureMessage);
-                samlResponse = buildResponse(authnRequest.getID(), new DateTime(), relyingParty.getProviderId(),
-                        failureStatus);
-                
-                return samlResponse;
-            }
+        final AuthnRequest authnRequest = requestContext.getAuthnRequest();
+        String issuer = requestContext.getIssuer();
+        final HttpSession session = requestContext.getHttpSession();
+        final RelyingPartyConfiguration relyingParty = requestContext.getRpConfig();
+        final SSOConfiguration ssoConfig = requestContext.getSsoConfig();
+        final SPSSODescriptor spDescriptor = requestContext.getSpDescriptor();
+        
+        LoginContext loginCtx = requestContext.getLoginContext();
+        if (loginCtx.getAuthenticationOK()) {
             
             // the user successfully authenticated.
             // build an authentication assertion.
@@ -213,30 +412,21 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
                     relyingParty.getProviderId(), buildStatus(StatusCode.SUCCESS_URI, null, null));
             
             DateTime now = new DateTime();
-            Assertion assertion = buildAssertion(now, relyingParty,
-                    (AbstractSAML2ProfileConfiguration) relyingParty.getProfileConfigurations().get(SSOConfiguration.PROFILE_ID));
-            assertion.setSubject(authnRequest.getSubject());
+            Assertion assertion = buildAssertion(now, relyingParty, (AbstractSAML2ProfileConfiguration) ssoConfig);
+            assertion.setSubject(requestContext.getSubject());
             setAuthenticationStatement(assertion, loginCtx, authnRequest);
-            
             samlResponse.getAssertions().add(assertion);
             
-            // retrieve the AssertionConsumerService endpoint (we parsed it in
-            // verifyAuthnRequest()
-            AssertionConsumerService acsEndpoint = getACSEndpointFromSession(session);
-            
-        } catch (AuthenticationRequestException ex) {
+        } else {
             
-            Status errorStatus = ex.getStatus();
-            if (errorStatus == null) {
-                // if no explicit status code was set,
-                // assume the error was in the message.
-                samlResponse = buildResponse(authnRequest.getID(),
-                        new DateTime(), relyingParty.getProviderId(),
-                        errorStatus);
-            }
+            // if authentication failed, encode the appropriate SAML error message.
+            String failureMessage = loginCtx.getAuthenticationFailureMessage();
+            Status failureStatus = buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, failureMessage);
+            samlResponse = buildResponse(authnRequest.getID(), new DateTime(), relyingParty.getProviderId(),
+                    failureStatus);
         }
         
-        return samlResponse;
+        requestContext.setResponse(samlResponse);
     }
     
     /**
@@ -274,59 +464,6 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
         return response;
     }
     
-    
-    /**
-     * Check that a request's issuer can be found in the metadata. If so, store
-     * the relevant metadata objects in the user's session.
-     *
-     * @param issuer
-     *            The issuer of the AuthnRequest.
-     * @param relyingParty
-     *            The RelyingPartyConfiguration for the issuer.
-     * @param ssoConfig
-     *            The SSOConfiguration for the relyingParty
-     * @param spDescriptor
-     *            The SPSSODescriptor for the ssoConfig.
-     *
-     * @return <code>true</code> if Metadata was found for the issuer;
-     *         otherwise, <code>false</code>.
-     */
-    protected boolean findMetadataForSSORequest(Issuer issuer,
-            RelyingPartyConfiguration relyingParty, SSOConfiguration ssoConfig,
-            SPSSODescriptor spDescriptor) {
-        
-        MetadataProvider metadataProvider = getRelyingPartyConfigurationManager()
-        .getMetadataProvider();
-        String providerId = issuer.getSPProvidedID();
-        relyingParty = getRelyingPartyConfigurationManager()
-        .getRelyingPartyConfiguration(providerId);
-        ssoConfig = (SSOConfiguration) relyingParty.getProfileConfigurations()
-        .get(SSOConfiguration.PROFILE_ID);
-        
-        try {
-            spDescriptor = metadataProvider.getEntityDescriptor(
-                    relyingParty.getRelyingPartyId()).getSPSSODescriptor(
-                    SAML20_PROTOCOL_URI);
-        } catch (MetadataProviderException ex) {
-            log.error(
-                    "SAML 2 Authentication Request: Unable to locate metadata for SP "
-                    + providerId + " for protocol "
-                    + SAML20_PROTOCOL_URI, ex);
-            return false;
-        }
-        
-        if (spDescriptor == null) {
-            log
-                    .error("SAML 2 Authentication Request: Unable to locate metadata for SP "
-                    + providerId
-                    + " for protocol "
-                    + SAML20_PROTOCOL_URI);
-            return false;
-        }
-        
-        return true;
-    }
-    
     /**
      * Check if the user has already been authenticated.
      *
@@ -345,83 +482,6 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
     }
     
     /**
-     * Store a user's AuthnRequest and Issuer in the session.
-     *
-     * @param authnRequest
-     *            A SAML 2 AuthnRequest.
-     * @param issuer
-     *            The issuer of the AuthnRequest.
-     * @param session
-     *            The HttpSession in which the data should be stored.
-     * @param relyingParty
-     *            The RelyingPartyConfiguration for the issuer.
-     * @param ssoConfig
-     *            The SSOConfiguration for the relyingParty
-     * @param spDescriptor
-     *            The SPSSODescriptor for the ssoConfig.
-     */
-    protected void storeRequestData(final HttpSession session,
-            final AuthnRequest authnRequest, final Issuer issuer,
-            final RelyingPartyConfiguration relyingParty,
-            final SSOConfiguration ssoConfig, final SPSSODescriptor spDescriptor) {
-        
-        if (session == null) {
-            return;
-        }
-        
-        session.setAttribute(AUTHNREQUEST_SESSION_KEY, authnRequest);
-        session.setAttribute(ISSUER_SESSION_KEY, issuer);
-        session.setAttribute(RPCONFIG_SESSION_KEY, relyingParty);
-        session.setAttribute(SSOCONFIG_SESSION_KEY, ssoConfig);
-        session.setAttribute(SPSSODESC_SESSION_KEY, spDescriptor);
-    }
-    
-    /**
-     * Retrieve the AuthnRequest and Issuer from a session.
-     *
-     * @param session
-     *            The HttpSession in which the data was stored.
-     * @param authnRequest
-     *            Will be populated with the AuthnRequest.
-     * @param issuer
-     *            Will be populated with the ssuer of the AuthnRequest.
-     * @param relyingParty
-     *            Will be populated with the RelyingPartyConfiguration for the
-     *            issuer.
-     * @param ssoConfig
-     *            Will be populated with the SSOConfiguration for the
-     *            relyingParty
-     * @param spDescriptor
-     *            Will be populated with the SPSSODescriptor for the ssoConfig.
-     */
-    protected void retrieveRequestData(final HttpSession session,
-            AuthnRequest authnRequest, Issuer issuer,
-            RelyingPartyConfiguration relyingParty, SSOConfiguration ssoConfig,
-            SPSSODescriptor spDescriptor) {
-        
-        if (session == null) {
-            authnRequest = null;
-            issuer = null;
-        }
-        
-        authnRequest = (AuthnRequest) session
-                .getAttribute(AUTHNREQUEST_SESSION_KEY);
-        issuer = (Issuer) session.getAttribute(ISSUER_SESSION_KEY);
-        relyingParty = (RelyingPartyConfiguration) session
-                .getAttribute(RPCONFIG_SESSION_KEY);
-        ssoConfig = (SSOConfiguration) session
-                .getAttribute(SSOCONFIG_SESSION_KEY);
-        spDescriptor = (SPSSODescriptor) session
-                .getAttribute(SPSSODESC_SESSION_KEY);
-        
-        session.removeAttribute(AUTHNREQUEST_SESSION_KEY);
-        session.removeAttribute(ISSUER_SESSION_KEY);
-        session.removeAttribute(RPCONFIG_SESSION_KEY);
-        session.removeAttribute(SSOCONFIG_SESSION_KEY);
-        session.removeAttribute(SPSSODESC_SESSION_KEY);
-    }
-    
-    /**
      * Check if the user has already been authenticated. If so, return the
      * LoginContext. If not, redirect the user to the AuthenticationManager.
      *
@@ -434,60 +494,64 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
      * @param response
      *            The user's HttpServletResponse.
      *
-     * @return A LoginContext for the authenticated user.
-     *
-     * @throws SerlvetException
+     * @throws ProfileException
      *             on error.
      */
-    protected void authenticateUser(final AuthnRequest authnRequest,
-            final HttpSession httpSession, final HttpServletRequest request,
-            final HttpServletResponse response) throws ServletException {
+    protected void authenticateUser(final AuthenticationRequestContext requestContext) throws ProfileException {
+        
+        AuthnRequest authnRequest = requestContext.getAuthnRequest();
+        HttpSession httpSession = requestContext.getHttpSession();
+        HttpServletRequest servletRequest = requestContext.getServletRequest();
+        HttpServletResponse servletResponse = requestContext.getServletResponse();
         
         // Forward the request to the AuthenticationManager.
         // When the AuthenticationManager is done it will
         // forward the request back to this servlet.
         
+        // push the AuthenticationRequestContext into the session so we have it
+        // for the return leg.
+        httpSession.setAttribute(REQUEST_CONTEXT_SESSION_KEY, requestContext);
+        
         Saml2LoginContext loginCtx = new Saml2LoginContext(authnRequest);
-        loginCtx.setProfileHandlerURL(request.getPathInfo());
+        requestContext.setLoginContext(loginCtx);
+        loginCtx.setProfileHandlerURL(servletRequest.getRequestURI());
+        
+        // the AuthenticationManager expects the LoginContext to be in the HttpSession.
         httpSession.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginCtx);
         try {
-            RequestDispatcher dispatcher = request
+            RequestDispatcher dispatcher = servletRequest
                     .getRequestDispatcher(authnMgrURL);
-            dispatcher.forward(request, response);
+            dispatcher.forward(servletRequest,servletResponse);
         } catch (IOException ex) {
             log.error("Error forwarding SAML 2 AuthnRequest "
                     + authnRequest.getID() + " to AuthenticationManager", ex);
-            throw new ServletException("Error forwarding SAML 2 AuthnRequest "
+            throw new ProfileException("Error forwarding SAML 2 AuthnRequest "
+                    + authnRequest.getID() + " 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);
         }
     }
     
     /**
-     * Build an AuthnStatement and add it to a Response.
+     * Build an AuthnStatement and add it to an Assertion.
      *
-     * @param response
-     *            The Response to which the AuthnStatement will be added.
-     * @param loginCtx
-     *            The LoginContext of the sucessfully authenticated user.
-     * @param authnRequest
-     *            The AuthnRequest that prompted this message.
-     * @param ssoConfig
-     *            The SSOConfiguration for the RP to which we are addressing
-     *            this message.
-     * @param issuer
-     *            The IdP's identifier.
-     * @param audiences
-     *            An array of URIs restricting the audience of this assertion.
+     * @param assertion An empty SAML 2 Assertion object.
+     * @param loginContext The processed login context for the AuthnRequest.
+     * @param authnRequest The AuthnRequest to which this is in response.
+     *
+     * @throws ProfileException On error.
      */
     protected void setAuthenticationStatement(Assertion assertion,
-            final Saml2LoginContext loginContext,
-            final AuthnRequest authnRequest) throws ServletException {
+            final LoginContext loginContext,
+            final AuthnRequest authnRequest) throws ProfileException {
         
-        // Build the AuthnCtx. We need to determine if the user was
-        // authenticated
+        // Build the AuthnCtx.
+        // We need to determine if the user was authenticated
         // with an AuthnContextClassRef or a AuthnContextDeclRef
-        AuthnContext authnCtx = buildAuthnCtx(authnRequest
-                .getRequestedAuthnContext(), loginContext);
+        AuthnContext authnCtx = buildAuthnCtx(authnRequest.getRequestedAuthnContext(), loginContext);
         if (authnCtx == null) {
             log.error("Error respond to SAML 2 AuthnRequest "
                     + authnRequest.getID()
@@ -511,14 +575,14 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
      *
      * @param requestedAuthnCtx
      *            The RequestedAuthnContext from the Authentication Request.
-     * @param authnMethod
-     *            The authentication method that was used.
+     * @param loginContext
+     *            The processed LoginContext (it must contain the authn method).
      *
      * @return An AuthnCtx object on success or <code>null</code> on failure.
      */
     protected AuthnContext buildAuthnCtx(
             final RequestedAuthnContext requestedAuthnCtx,
-            final Saml2LoginContext loginContext) {
+            final LoginContext loginContext) {
         
         // this method assumes that only one URI will match.
         
@@ -564,40 +628,6 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
     }
     
     /**
-     * Get the user's LoginContext.
-     *
-     * @param httpSession
-     *            The user's HttpSession.
-     *
-     * @return The user's LoginContext.
-     *
-     * @throws ServletException
-     *             On error.
-     */
-    protected Saml2LoginContext getLoginContext(final HttpSession httpSession)
-    throws ServletException {
-        
-        Object o = httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
-        if (o == null) {
-            log.error("User's session does not contain a LoginContext object.");
-            throw new ServletException(
-                    "User's session does not contain a LoginContext object.");
-        }
-        
-        if (!(o instanceof Saml2LoginContext)) {
-            log
-                    .error("Invalid login context object -- object is not an instance of Saml2LoginContext.");
-            throw new ServletException("Invalid login context object.");
-        }
-        
-        Saml2LoginContext ctx = (Saml2LoginContext) o;
-        
-        httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
-        
-        return ctx;
-    }
-    
-    /**
      * Verify the AuthnRequest is well-formed.
      *
      * @param authnRequest
@@ -612,40 +642,38 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
      * @throws AuthenticationRequestException
      *             on error.
      */
-    protected void verifyAuthnRequest(final AuthnRequest authnRequest,
-            Issuer issuer, final RelyingPartyConfiguration relyingParty,
-            final HttpSession session) throws AuthenticationRequestException {
+    protected void verifyAuthnRequest(final AuthenticationRequestContext requestContext) throws AuthenticationRequestException {
+        
+        final AuthnRequest authnRequest = requestContext.getAuthnRequest();
+        String issuer = requestContext.getIssuer();
+        final RelyingPartyConfiguration relyingParty = requestContext.getRpConfig();
+        final HttpSession session = requestContext.getHttpSession();
         
         Status failureStatus;
         
         // Check if we are in scope to handle this AuthnRequest
-        checkScope(authnRequest, issuer.getSPProvidedID());
-        
-        // XXX: run signature checks on authnRequest
+        checkScope(authnRequest, issuer);
         
         // verify that the AssertionConsumerService url is valid.
-        AssertionConsumerService acsEndpoint = getAndVerifyACSEndpoint(
-                authnRequest, relyingParty.getRelyingPartyId(),
+        verifyAssertionConsumerService(requestContext,
                 getRelyingPartyConfigurationManager().getMetadataProvider());
-        session.setAttribute(ACS_SESSION_KEY, acsEndpoint);
         
         // check for nameID constraints.
-        Subject subject = getAndVerifySubject(authnRequest);
+        verifySubject(requestContext);
     }
     
     /**
      * Get and verify the Subject element.
      *
-     * @param authnRequest
-     *            The SAML 2 AuthnRequest.
-     *
-     * @return A Subject element.
-     *
+     * @param requestContext The context for the current request.
+     * 
      * @throws AuthenticationRequestException
      *             on error.
      */
-    protected Subject getAndVerifySubject(final AuthnRequest authnRequest)
-    throws AuthenticationRequestException {
+    protected void verifySubject(final AuthenticationRequestContext requestContext)
+            throws AuthenticationRequestException {
+        
+        final AuthnRequest authnRequest = requestContext.getAuthnRequest();
         
         Status failureStatus;
         
@@ -679,32 +707,95 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
                     failureStatus);
         }
         
-        return subject;
+        requestContext.setSubject(subject);
+        
+        return;
+    }
+    
+    /**
+     * Ensure that metadata can be found for the SP that issued
+     * the AuthnRequest.
+     *
+     * If found, the request context is updated to reflect the appropriate entries.
+     *
+     * Before this method may be called, the request context must have an issuer set.
+     *
+     * @param requestContext The context for the current request.
+     *
+     * @throws AuthenticationRequestException On error.
+     */
+    protected void validateRequestAgainstMetadata(final AuthenticationRequestContext requestContext) throws AuthenticationRequestException {
+        
+        RelyingPartyConfiguration relyingParty = null;
+        SSOConfiguration ssoConfig = null;
+        SPSSODescriptor spDescriptor = null;
+        
+        // check that we have metadata for the RP
+        relyingParty = getRelyingPartyConfigurationManager().getRelyingPartyConfiguration(requestContext.getIssuer());
+        
+        ProfileConfiguration temp = relyingParty.getProfileConfigurations().get(SSOConfiguration.PROFILE_ID);
+        if (temp == null) {
+            log.error("SAML 2 Authentication Request: No profile configuration registered for " + SSOConfiguration.PROFILE_ID);
+            throw new AuthenticationRequestException("No profile configuration registered for " + SSOConfiguration.PROFILE_ID);
+        }
+        
+        ssoConfig = (SSOConfiguration) temp;
+        
+        try {
+            spDescriptor = getMetadataProvider().getEntityDescriptor(
+                    relyingParty.getRelyingPartyId()).getSPSSODescriptor(
+                    SAML20_PROTOCOL_URI);
+        } catch (MetadataProviderException ex) {
+            log.error(
+                    "SAML 2 Authentication Request: Unable to locate SPSSODescriptor for SP "
+                    + requestContext.getIssuer() + " for protocol " + SAML20_PROTOCOL_URI, ex);
+            
+            Status failureStatus = buildStatus(StatusCode.REQUESTER_URI, null,
+                    "No metadata available for " + relyingParty.getRelyingPartyId());
+            
+            throw new AuthenticationRequestException("SAML 2 Authentication Request: Unable to locate SPSSODescriptor for SP "
+                    + requestContext.getIssuer() + " for protocol " + SAML20_PROTOCOL_URI, ex, failureStatus);
+        }
+        
+        if (spDescriptor == null) {
+            log.error("SAML 2 Authentication Request: Unable to locate SPSSODescriptor for SP "
+                    + requestContext.getIssuer() + " for protocol " + SAML20_PROTOCOL_URI);
+
+            Status failureStatus = buildStatus(StatusCode.REQUESTER_URI, null,
+                    "No metadata available for " + relyingParty.getRelyingPartyId());
+            
+            throw new AuthenticationRequestException("SAML 2 Authentication Request: Unable to locate SPSSODescriptor for SP "
+                    + requestContext.getIssuer() + " for protocol " + SAML20_PROTOCOL_URI, failureStatus);
+        }
+        
+        // if all metadata was found, update the request context.
+        requestContext.setRpConfig(relyingParty);
+        requestContext.setSsoConfig(ssoConfig);
+        requestContext.setSpDescriptor(spDescriptor);
     }
     
     /**
      * Return the endpoint URL and protocol binding to use for the AuthnRequest.
      *
-     * @param authnRequest
-     *            The SAML 2 AuthnRequest.
-     * @param providerId
-     *            The SP's providerId.
+     * @param requestContext The context for the current request.
+     * 
      * @param metadata
      *            The appropriate Metadata.
      *
-     * @return The AssertionConsumerService for the endpoint, or
-     *         <code>null</code> on error.
-     *
      * @throws AuthenticationRequestException
      *             On error.
      */
-    protected AssertionConsumerService getAndVerifyACSEndpoint(
-            final AuthnRequest authnRequest, String providerId,
+    protected void verifyAssertionConsumerService(
+            final AuthenticationRequestContext requestContext,
+            
             final MetadataProvider metadata)
             throws AuthenticationRequestException {
         
         Status failureStatus;
         
+        final AuthnRequest authnRequest = requestContext.getAuthnRequest();
+        String providerId = requestContext.getRpConfig().getRelyingPartyId();
+        
         // Either the AssertionConsumerServiceIndex must be present
         // or AssertionConsumerServiceURL must be present.
         
@@ -729,7 +820,7 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
         SPSSODescriptor spDescriptor;
         try {
             spDescriptor = metadata.getEntityDescriptor(providerId)
-            .getSPSSODescriptor(SAML20_PROTOCOL_URI);
+                    .getSPSSODescriptor(SAML20_PROTOCOL_URI);
         } catch (MetadataProviderException ex) {
             log.error(
                     "Unable retrieve SPSSODescriptor metadata for providerId "
@@ -765,7 +856,8 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
                         failureStatus);
             }
             
-            return acsList.get(i);
+            requestContext.setAssertionConsumerService(acsList.get(i));
+            return;
         }
         
         // if the ACS endpoint is specified, validate it against the metadata
@@ -774,7 +866,8 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
             if (acsURL.equals(acs.getLocation())) {
                 if (protocolBinding != null) {
                     if (protocolBinding.equals(acs.getBinding())) {
-                        return acs;
+                        requestContext.setAssertionConsumerService(acs);
+                        return;
                     }
                 }
             }
@@ -795,43 +888,6 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
     }
     
     /**
-     * Retrieve a parsed AssertionConsumerService endpoint from the user's
-     * session.
-     *
-     * @param session
-     *            The user's HttpSession.
-     *
-     * @return An AssertionConsumerServiceEndpoint object.
-     *
-     * @throws ServletException
-     *             On error.
-     */
-    protected AssertionConsumerService getACSEndpointFromSession(
-            final HttpSession session) throws ServletException {
-        
-        Object o = session.getAttribute(ACS_SESSION_KEY);
-        if (o == null) {
-            log
-                    .error("User's session does not contain an AssertionConsumerService object.");
-            throw new ServletException(
-                    "User's session does not contain an AssertionConsumerService object.");
-        }
-        
-        if (!(o instanceof AssertionConsumerService)) {
-            log
-                    .error("Invalid session data -- object is not an instance of AssertionConsumerService.");
-            throw new ServletException(
-                    "Invalid session data -- object is not an instance of AssertionConsumerService.");
-        }
-        
-        AssertionConsumerService endpoint = (AssertionConsumerService) o;
-        
-        session.removeAttribute(ACS_SESSION_KEY);
-        
-        return endpoint;
-    }
-    
-    /**
      * Check if an {@link AuthnRequest} contains a {@link Scoping} element. If
      * so, check if the specified IdP is in the {@link IDPList} element. If no
      * Scoping element is present, this method returns <code>true</code>.
@@ -845,7 +901,7 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
      *             on error.
      */
     protected void checkScope(final AuthnRequest authnRequest, String providerId)
-    throws AuthenticationRequestException {
+            throws AuthenticationRequestException {
         
         Status failureStatus;
         
@@ -898,7 +954,7 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
         }
         
         log.error("SAML 2 AuthnRequest " + authnRequest.getID()
-        + " contains a Scoping element which "
+                + " contains a Scoping element which "
                 + "does not contain a providerID registered with this IdP.");
         
         failureStatus = buildStatus(StatusCode.RESPONDER_URI,
@@ -944,7 +1000,7 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
             Document doc = parserPool.parse(istream);
             Element docElement = doc.getDocumentElement();
             Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory()
-            .getUnmarshaller(docElement);
+                    .getUnmarshaller(docElement);
             idpList = (IDPList) unmarshaller.unmarshall(docElement);
             
         } catch (MalformedURLException ex) {
@@ -954,10 +1010,6 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
         } catch (IOException ex) {
             log.error("IO Error while retreieving GetComplete IDPList from "
                     + uri, ex);
-        } catch (ConfigurationException ex) {
-            log.error(
-                    "Internal OpenSAML error while parsing GetComplete IDPList from "
-                    + uri, ex);
         } catch (XMLParserException ex) {
             log.error(
                     "Internal OpenSAML error while parsing GetComplete IDPList from "
@@ -979,4 +1031,47 @@ public abstract class AbstractAuthenticationRequest extends AbstractSAML2Profile
         
         return idpList;
     }
+    
+    /**
+     * Encode a SAML Response.
+     *
+     * @param binding The SAML protocol binding to use.
+     * @param requestContext The context for the request.
+     *
+     * @throws ProfileException On error.
+     */
+    protected void encodeResponse(String binding,
+            final AuthenticationRequestContext requestContext) throws ProfileException {
+        
+        final ProfileResponse<ServletResponse> profileResponse = requestContext.getProfileResponse();
+        final Response samlResponse = requestContext.getResponse();
+        final RelyingPartyConfiguration relyingParty = requestContext.getRpConfig();
+        final RoleDescriptor roleDescriptor = requestContext.getSpDescriptor();
+        final Endpoint endpoint = requestContext.getAssertionConsumerService();
+        
+        
+        MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(binding);
+        if (encoder == null) {
+            log.error("No MessageEncoder registered for " + binding);
+            throw new ProfileException("No MessageEncoder registered for " + binding);
+        }
+        
+        encoder.setResponse(profileResponse.getRawResponse());
+        encoder.setIssuer(relyingParty.getProviderId());
+        encoder.setMetadataProvider(getRelyingPartyConfigurationManager().getMetadataProvider());
+        encoder.setRelyingPartyRole(roleDescriptor);
+        encoder.setSigningCredential(relyingParty.getDefaultSigningCredential());
+        encoder.setSamlMessage(samlResponse);
+        encoder.setRelyingPartyEndpoint(endpoint);
+        
+        try {
+            encoder.encode();
+        } catch (BindingException ex) {
+            log.error("Unable to encode response the relying party: " + relyingParty.getRelyingPartyId(), ex);
+            throw new ProfileException("Unable to encode response the relying party: "
+                    + relyingParty.getRelyingPartyId(), ex);
+        }
+        
+    }
+    
 }