protected override void OnLoad(System.EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                // Process the artifact resolve request received from the identity provider in response
                // to the artifact sent by the service provider.

                ArtifactResolve artifactResolve = ArtifactResolve.Create(Request);

                // Get the artifact.
                Saml2ArtifactType0004 httpArtifact = new Saml2ArtifactType0004(artifactResolve.Artifact.ArtifactValue);

                // Remove the artifact state from the cache.
                XmlElement artifactXml = (XmlElement)SamlSettings.CacheProvider.Remove(httpArtifact.ToString());
                if (artifactXml == null)
                {
                    return;
                }

                // Create an artifact response containing the cached SAML message.
                ArtifactResponse artifactResponse = new ArtifactResponse();
                artifactResponse.Issuer  = new Issuer(Util.GetAbsoluteUrl(this, "~/"));
                artifactResponse.Message = artifactXml;

                // Send the artifact response.
                artifactResponse.Send(Response);
            }

            catch (System.Exception exception)
            {
                Trace.Write("ServiceProvider", "Error in artifact responder", exception);
            }
        }
 /// <summary>
 /// Loads the current message as an artifact resolve.
 /// </summary>
 private void LoadArtifactResolve()
 {
     if (_artifactResolve == null)
     {
         _artifactResolve = Serialization.Deserialize <ArtifactResolve>(new XmlNodeReader(SamlMessage));
     }
 }
Exemple #3
0
        protected override void OnLoad(System.EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                // Receive the artifact resolve request.
                ArtifactResolve artifactResolve = ArtifactResolve.Create(Request);

                // Get the artifact.
                Saml2ArtifactType0004 httpArtifact = new Saml2ArtifactType0004(artifactResolve.Artifact.ArtifactValue);

                // Remove the artifact state from the cache.
                XmlElement samlResponseXml = (XmlElement)SamlSettings.CacheProvider.Remove(httpArtifact.ToString());

                if (samlResponseXml == null)
                {
                    return;
                }

                // Create an artifact response containing the cached SAML message.
                ArtifactResponse artifactResponse = new ArtifactResponse();
                artifactResponse.Issuer  = new Issuer(new Uri(Request.Url, ResolveUrl("~/")).ToString());
                artifactResponse.Message = samlResponseXml;

                // Send the artifact response.
                artifactResponse.Send(Response);
            }
            catch (Exception exception)
            {
                Trace.Write("ServiceProvider", "An Error occurred", exception);
            }
        }
Exemple #4
0
        /// <summary>
        /// Handles responses to an artifact resolve message.
        /// </summary>
        /// <param name="idpEndPoint">The IdP endpoint</param>
        /// <param name="artifactResolve">The artifact resolve message.</param>
        public void RespondToArtifactResolve(IDPEndPoint idpEndPoint, ArtifactResolve artifactResolve)
        {
            XmlDocument samlDoc = (XmlDocument)_context.Cache.Get(artifactResolve.Artifact);

            Saml20ArtifactResponse response = Saml20ArtifactResponse.GetDefault();

            response.StatusCode   = Saml20Constants.StatusCodes.Success;
            response.InResponseTo = artifactResolve.ID;
            response.SamlElement  = samlDoc.DocumentElement;

            XmlDocument responseDoc = response.GetXml();

            if (responseDoc.FirstChild is XmlDeclaration)
            {
                responseDoc.RemoveChild(responseDoc.FirstChild);
            }

            var signingCertificate  = FederationConfig.GetConfig().GetFirstValidCertificate();
            var shaHashingAlgorithm = SignatureProviderFactory.ValidateShaHashingAlgorithm(idpEndPoint.ShaHashingAlgorithm);
            var signatureProvider   = SignatureProviderFactory.CreateFromShaHashingAlgorithmName(shaHashingAlgorithm);

            signatureProvider.SignAssertion(responseDoc, response.ID, signingCertificate);

            if (Trace.ShouldTrace(TraceEventType.Information))
            {
                Trace.TraceData(TraceEventType.Information, string.Format(Tracing.RespondToArtifactResolve, artifactResolve.Artifact, responseDoc.OuterXml));
            }
            SendResponseMessage(responseDoc.OuterXml);
        }
Exemple #5
0
        // Process the artifact resolve request received from the identity provider in response
        // to the artifact sent by the service provider.
        private void ProcessArtifactResolve()
        {
            Trace.Write("IdP", "Processing artifact resolve request");

            // Receive the artifact resolve request.
            XmlElement      artifactResolveXml = ArtifactResolver.ReceiveArtifactResolve(Request);
            ArtifactResolve artifactResolve    = new ArtifactResolve(artifactResolveXml);

            // Get the artifact.
            HTTPArtifactType4 httpArtifact = new HTTPArtifactType4(artifactResolve.Artifact.ArtifactValue);

            // Remove the artifact state from the cache.
            HTTPArtifactState httpArtifactState = HTTPArtifactStateCache.Remove(httpArtifact);

            if (httpArtifactState == null)
            {
                throw new ArgumentException("Invalid artifact.");
            }

            // Create an artifact response containing the cached SAML message.
            ArtifactResponse artifactResponse = new ArtifactResponse();

            artifactResponse.Issuer      = new Issuer(CreateAbsoluteURL("~/"));
            artifactResponse.SAMLMessage = httpArtifactState.SAMLMessage;

            XmlElement artifactResponseXml = artifactResponse.ToXml();

            // Send the artifact response.
            ArtifactResolver.SendArtifactResponse(Response, artifactResponseXml);

            Trace.Write("IdP", "Processed artifact resolve request");
        }
Exemple #6
0
        /// <summary>
        /// Handles responses to an artifact resolve message.
        /// </summary>
        /// <param name="artifactResolve">The artifact resolve message.</param>
        public void RespondToArtifactResolve(ArtifactResolve artifactResolve)
        {
            XmlDocument samlDoc = (XmlDocument)_context.Cache.Get(artifactResolve.Artifact);

            Saml20ArtifactResponse response = Saml20ArtifactResponse.GetDefault();

            response.StatusCode   = Saml20Constants.StatusCodes.Success;
            response.InResponseTo = artifactResolve.ID;
            response.SamlElement  = samlDoc.DocumentElement;

            XmlDocument responseDoc = response.GetXml();

            if (responseDoc.FirstChild is XmlDeclaration)
            {
                responseDoc.RemoveChild(responseDoc.FirstChild);
            }

            XmlSignatureUtils.SignDocument(responseDoc, response.ID);

            if (Trace.ShouldTrace(TraceEventType.Information))
            {
                Trace.TraceData(TraceEventType.Information, string.Format(Tracing.RespondToArtifactResolve, artifactResolve.Artifact, responseDoc.OuterXml));
            }
            SendResponseMessage(responseDoc.OuterXml);
        }
        // Process the artifact resolve request received from the identity provider in response
        // to the artifact sent by the service provider.
        private void ProcessArtifactResolve()
        {
            Trace.Write("IdP", "Processing artifact resolve request");

            // Receive the artifact resolve request.
            XmlElement artifactResolveXml = ArtifactResolver.ReceiveArtifactResolve(Request);
            ArtifactResolve artifactResolve = new ArtifactResolve(artifactResolveXml);

            // Get the artifact.
            HTTPArtifactType4 httpArtifact = new HTTPArtifactType4(artifactResolve.Artifact.ArtifactValue);

            // Remove the artifact state from the cache.
            HTTPArtifactState httpArtifactState = HTTPArtifactStateCache.Remove(httpArtifact);

            if (httpArtifactState == null) {
                return;
            }

            // Create an artifact response containing the cached SAML message.
            ArtifactResponse artifactResponse = new ArtifactResponse();
            artifactResponse.Issuer = new Issuer(CreateAbsoluteURL("~/"));
            artifactResponse.SAMLMessage = httpArtifactState.SAMLMessage;

            XmlElement artifactResponseXml = artifactResponse.ToXml();

            // Send the artifact response.
            ArtifactResolver.SendArtifactResponse(Response, artifactResponseXml);

            Trace.Write("IdP", "Processed artifact resolve request");
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                // Get the artifact resolve request.
                ArtifactResolve artifactResolve = ArtifactResolve.Create(Request);

                // Create a new artifact.
                Saml2ArtifactType0004 httpArtifact = new Saml2ArtifactType0004(artifactResolve.Artifact.ArtifactValue);

                // Remove the artifact state from the cache.
                XmlElement samlResponseXml = (XmlElement)SamlSettings.CacheProvider.Remove(httpArtifact.ToString());
                if (samlResponseXml == null)
                {
                    throw new ApplicationException("Invalid artifact.");
                }

                // Create an artifact response containing the cached SAML message.
                ArtifactResponse artifactResponse = new ArtifactResponse();
                artifactResponse.Issuer  = new Issuer(Util.GetAbsoluteUrl(this, "~/"));
                artifactResponse.Message = samlResponseXml;

                // Send the artifact response.
                artifactResponse.Send(Response);
            }

            catch (Exception exception)
            {
                Trace.Write("ServiceProvider", "An Error occurred", exception);
            }
        }
Exemple #9
0
        // Receive the SAML response from the identity provider.
        private void ReceiveSAMLResponse(out SAMLResponse samlResponse, out string relayState)
        {
            // Rather than separate endpoints per binding, we have a single endpoint and use a query string
            // parameter to determine the identity provider to service provider binding type.
            string bindingType = Request.QueryString[bindingQueryParameter];

            Trace.Write("SP", "Receiving SAML response over binding " + bindingType);

            // Receive the SAML response over the specified binding.
            XmlElement samlResponseXml = null;

            switch (bindingType)
            {
            case BindingTypes.Post:
                ServiceProvider.ReceiveSAMLResponseByHTTPPost(Request, out samlResponseXml, out relayState);
                break;

            case BindingTypes.Artifact:
                // Receive the artifact.
                HTTPArtifact httpArtifact = null;

                ServiceProvider.ReceiveArtifactByHTTPArtifact(Request, false, out httpArtifact, out relayState);

                // Create an artifact resolve request.
                ArtifactResolve artifactResolve = new ArtifactResolve();
                artifactResolve.Issuer   = new Issuer(CreateAbsoluteURL("~/"));
                artifactResolve.Artifact = new Artifact(httpArtifact.ToString());

                XmlElement artifactResolveXml = artifactResolve.ToXml();

                // Send the artifact resolve request and receive the artifact response.
                XmlElement artifactResponseXml = ArtifactResolver.SendRequestReceiveResponse(Configuration.ArtifactResolutionServiceURL, artifactResolveXml);

                ArtifactResponse artifactResponse = new ArtifactResponse(artifactResponseXml);

                // Extract the authentication request from the artifact response.
                samlResponseXml = artifactResponse.SAMLMessage;
                break;

            default:
                throw new ArgumentException("Unknown binding type");
            }

            // Verify the response's signature.
            if (SAMLMessageSignature.IsSigned(samlResponseXml))
            {
                Trace.Write("SP", "Verifying response signature");
                X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.IdPX509Certificate];

                if (!SAMLMessageSignature.Verify(samlResponseXml, x509Certificate))
                {
                    throw new ArgumentException("The SAML response signature failed to verify.");
                }
            }

            // Deserialize the XML.
            samlResponse = new SAMLResponse(samlResponseXml);

            Trace.Write("SP", "Received SAML response");
        }
Exemple #10
0
        // Receive the SAML response from the identity provider.
        private void ReceiveSAMLResponse(ref SAMLResponse samlResponse, ref string relayState)
        {
            Trace.Write("SP", "Receiving SAML response");

            // Determine the identity provider to service provider binding type.
            // We use a query string parameter rather than having separate endpoints per binding.
            string bindingType = Request.QueryString[bindingQueryParameter];

            // Receive the SAML response over the specified binding.
            XmlElement samlResponseXml = null;

            switch (bindingType)
            {
            case SAMLIdentifiers.BindingURIs.HTTPPost:
                ServiceProvider.ReceiveSAMLResponseByHTTPPost(Request, out samlResponseXml, out relayState);
                break;

            case SAMLIdentifiers.BindingURIs.HTTPArtifact:
                // Receive the artifact.
                HTTPArtifact httpArtifact = null;

                ServiceProvider.ReceiveArtifactByHTTPArtifact(Request, false, out httpArtifact, out relayState);

                // Create an artifact resolve request.
                ArtifactResolve artifactResolve = new ArtifactResolve();
                artifactResolve.Issuer   = new Issuer(CreateAbsoluteURL("~/"));
                artifactResolve.Artifact = new Artifact(httpArtifact.ToString());

                XmlElement artifactResolveXml = artifactResolve.ToXml();

                // Send the artifact resolve request and receive the artifact response.
                string spArtifactResponderURL = WebConfigurationManager.AppSettings["idpArtifactResponderURL"];

                XmlElement artifactResponseXml = ArtifactResolver.SendRequestReceiveResponse(spArtifactResponderURL, artifactResolveXml);

                ArtifactResponse artifactResponse = new ArtifactResponse(artifactResponseXml);

                // Extract the SAML response from the artifact response.
                samlResponseXml = artifactResponse.SAMLMessage;
                break;

            default:
                Trace.Write("SP", "Invalid identity provider to service provider binding");
                return;
            }

            // Verify the response's signature.
            X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.IdPX509Certificate];

            if (!SAMLMessageSignature.Verify(samlResponseXml, x509Certificate))
            {
                throw new ArgumentException("The SAML response signature failed to verify.");
            }

            // Deserialize the XML.
            samlResponse = new SAMLResponse(samlResponseXml);

            Trace.Write("SP", "Received SAML response");
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="Saml20ArtifactResolve"/> class.
 /// </summary>
 public Saml20ArtifactResolve()
 {
     _artifactResolve              = new ArtifactResolve();
     _artifactResolve.Version      = Saml20Constants.Version;
     _artifactResolve.ID           = "id" + Guid.NewGuid().ToString("N");
     _artifactResolve.Issuer       = new NameID();
     _artifactResolve.IssueInstant = DateTime.Now;
 }
Exemple #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Saml20ArtifactResolve"/> class.
 /// </summary>
 public Saml20ArtifactResolve()
 {
     _artifactResolve = new ArtifactResolve
                            {
                                Version = Saml20Constants.Version,
                                Id = "id" + Guid.NewGuid().ToString("N"),
                                Issuer = new NameId(),
                                IssueInstant = DateTime.Now
                            };
 }
        /// <summary>
        /// Processes the authentication request.
        /// </summary>
        /// <param name="authnRequest">The AuthnRequest object.</param>
        /// <param name="relayState">The relayState string.</param>
        public static void ProcessAuthnRequest(Page page, out AuthnRequest authnRequest, out string relayState)
        {
            // Use a single endpoint and use a query string parameter to determine the Service Provider to Identity Provider binding type.
            string bindingType = page.Request.QueryString[SP2IdPBindingTypeVar];

            // Get the previously loaded certificate.
            X509Certificate2 cert = (X509Certificate2)page.Application[Global.SPCertKey];

            switch (bindingType)
            {
            case RedirectBinding:
                authnRequest = AuthnRequest.Create(page.Request.RawUrl, cert.PublicKey.Key);
                relayState   = authnRequest.RelayState;
                break;

            case PostBinding:
                authnRequest = AuthnRequest.CreateFromHttpPost(page.Request);
                relayState   = authnRequest.RelayState;
                break;

            case ArtifactBinding:
                Saml2ArtifactType0004 httpArtifact = Saml2ArtifactType0004.CreateFromHttpArtifactHttpForm(page.Request);

                // Create an artifact resolve request.
                ArtifactResolve artifactResolve = new ArtifactResolve();
                artifactResolve.Issuer   = new Issuer(new Uri(page.Request.Url, page.ResolveUrl("~/")).ToString());
                artifactResolve.Artifact = new Artifact(httpArtifact.ToString());

                // Send the SAML Artifact Resolve Request and parse the received response.
                ArtifactResponse artifactResponse = ArtifactResponse.SendSamlMessageReceiveAftifactResponse(Global.ArtifactResolutionUrl, artifactResolve);

                // Extract the authentication request from the received artifact response.
                authnRequest = new AuthnRequest(artifactResponse.Message);
                relayState   = httpArtifact.RelayState;
                break;

            default:
                throw new ApplicationException("Invalid binding type");
            }

            if (authnRequest.IsSigned())
            {
                if (!authnRequest.Validate(cert))
                {
                    throw new ApplicationException("The authentication request signature failed to verify.");
                }
            }
        }
Exemple #14
0
        /// <summary>
        /// Processes the SAML response received from the IdP.
        /// </summary>
        /// <param name="page">The page object.</param>
        /// <param name="relayState">The relay state</param>
        /// <param name="samlResponse">The SAML response object.</param>
        public static void ProcessResponse(Page page, out ComponentPro.Saml2.Response samlResponse, out string relayState)
        {
            // Extract the binding type from the query string.
            string bindingType = page.Request.QueryString["binding"];

            switch (bindingType)
            {
                case "artifact":
                    // Create an artifact from the query string.
                    Saml2ArtifactType0004 httpArtifact = Saml2ArtifactType0004.CreateFromHttpArtifactQueryString(page.Request);

                    // Create an artifact resolve request.
                    ArtifactResolve artifactResolve = new ArtifactResolve();
                    artifactResolve.Issuer = new Issuer(GetAbsoluteUrl(page, "~/"));
                    artifactResolve.Artifact = new Artifact(httpArtifact.ToString());

                    // Send the artifact resolve request and create an artifact response from the received XML.
                    ArtifactResponse artifactResponse = ArtifactResponse.SendSamlMessageReceiveAftifactResponse(Global.ArtifactServiceUrl, artifactResolve);

                    // Get the SAML Response from the artifact response.
                    samlResponse = new ComponentPro.Saml2.Response(artifactResponse.Message);
                    relayState = httpArtifact.RelayState;
                    break;

                case "post":
                    System.Diagnostics.Debug.WriteLine("POST");
                    // Create a SAML response from the form data.
                    samlResponse = ComponentPro.Saml2.Response.Create(page.Request);
                    relayState = samlResponse.RelayState;
                    break;                

                default:
                    throw new ApplicationException("Unknown binding type");
            }

            // Is the SAML response signed?
            if (samlResponse.IsSigned())
            {
                // Get the previously loaded certificate.
                X509Certificate2 x509Certificate = (X509Certificate2)page.Application[Global.IdPCertKey];

                // Validate the certificate.
                if (!samlResponse.Validate(x509Certificate))
                {
                    throw new ApplicationException("The SAML response signature failed to verify.");
                }
            }
        }
Exemple #15
0
        /// <summary>
        /// Processes the SAML response received from the IdP.
        /// </summary>
        /// <param name="page">The page object.</param>
        /// <param name="relayState">The relay state</param>
        /// <param name="samlResponse">The SAML response object.</param>
        public static void ProcessResponse(Page page, out ComponentPro.Saml2.Response samlResponse, out string relayState)
        {
            // Extract the binding type from the query string.
            string bindingType = page.Request.QueryString["binding"];

            switch (bindingType)
            {
                case "artifact":
                    // Create an artifact from the query string.
                    Saml2ArtifactType0004 httpArtifact = Saml2ArtifactType0004.CreateFromHttpArtifactQueryString(page.Request);

                    // Create an artifact resolve request.
                    ArtifactResolve artifactResolve = new ArtifactResolve();
                    artifactResolve.Issuer = new Issuer(GetAbsoluteUrl(page, "~/"));
                    artifactResolve.Artifact = new Artifact(httpArtifact.ToString());

                    // Send the artifact resolve request and create an artifact response from the received XML.
                    ArtifactResponse artifactResponse = ArtifactResponse.SendSamlMessageReceiveAftifactResponse(Global.ArtifactServiceUrl, artifactResolve);

                    // Get the SAML Response from the artifact response.
                    samlResponse = new ComponentPro.Saml2.Response(artifactResponse.Message);
                    relayState = httpArtifact.RelayState;
                    break;

                case "post":
                    // Create a SAML response from the form data.
                    samlResponse = ComponentPro.Saml2.Response.Create(page.Request);
                    relayState = samlResponse.RelayState;
                    break;

                default:
                    throw new ApplicationException("Unknown binding type");
            }

            // Is the SAML response signed?
            if (samlResponse.IsSigned())
            {
                // Get the previously loaded certificate.
                X509Certificate2 x509Certificate = (X509Certificate2)page.Application[Global.IdPCertKey];

                // Validate the certificate.
                if (!samlResponse.Validate(x509Certificate))
                {
                    throw new ApplicationException("The SAML response signature failed to verify.");
                }
            }
        }
Exemple #16
0
        /// <summary>
        /// Receives the SAML response from the identity provider.
        /// </summary>
        /// <param name="samlResponse"></param>
        /// <param name="relayState"></param>
        private void ReceiveResponse(out ComponentPro.Saml2.Response samlResponse, out string relayState)
        {
            // Determine the identity provider to service provider binding type.
            // We use a query string parameter rather than having separate endpoints per binding.
            string bindingType = Request.QueryString[Util.BindingVarName];

            switch (bindingType)
            {
            case SamlBindingUri.HttpPost:
                samlResponse = ComponentPro.Saml2.Response.Create(Request);
                relayState   = samlResponse.RelayState;
                break;

            case SamlBindingUri.HttpArtifact:
                Saml2ArtifactType0004 httpArtifact = Saml2ArtifactType0004.CreateFromHttpArtifactHttpForm(Request);

                // Create an artifact resolve request.
                ArtifactResolve artifactResolve = new ArtifactResolve();
                artifactResolve.Issuer   = new Issuer(Util.GetAbsoluteUrl(this, "~/"));
                artifactResolve.Artifact = new Artifact(httpArtifact.ToString());

                // Send the artifact resolve request and receive the artifact response.
                string spArtifactResponderUrl = WebConfigurationManager.AppSettings["ArtifactIdProviderUrl"];

                ArtifactResponse artifactResponse = ArtifactResponse.SendSamlMessageReceiveAftifactResponse(spArtifactResponderUrl, artifactResolve);

                // Extract the authentication request from the artifact response.
                samlResponse = new Response(artifactResponse.Message);
                relayState   = httpArtifact.RelayState;
                break;

            default:
                Trace.Write("ServiceProvider", "Invalid identity provider to service provider binding");
                samlResponse = null;
                relayState   = null;
                return;
            }

            // Verify the response's signature.
            X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.IdPCertKey];

            if (!samlResponse.Validate(x509Certificate))
            {
                throw new System.ApplicationException("The SAML response signature failed to verify.");
            }
        }
        protected Saml2Request UnbindInternal(HttpRequestBase request, ArtifactResolve saml2RequestResponse, string messageName, X509Certificate2 signatureValidationCertificate)
        {
            base.UnbindInternal(request, saml2RequestResponse, signatureValidationCertificate);

            if (!"GET".Equals(request.HttpMethod, StringComparison.InvariantCultureIgnoreCase))
                throw new InvalidSaml2BindingException("Not HTTP POST Method.");

            if (!request.QueryString.AllKeys.Contains(messageName))
                throw new Saml2BindingException("QueryString does not contain " + messageName);

            if (request.QueryString.AllKeys.Contains(Saml2Constants.Message.RelayState))
            {
                RelayState = request.QueryString[Saml2Constants.Message.RelayState];
            }

            saml2RequestResponse.Artifact = request.QueryString[messageName];

            return saml2RequestResponse;
        }
Exemple #18
0
        /// <summary>
        /// Handles responses to an artifact resolve message.
        /// </summary>
        /// <param name="artifactResolve">The artifact resolve message.</param>
        public void RespondToArtifactResolve(ArtifactResolve artifactResolve, XmlElement samlDoc)
        {
            var response = Saml20ArtifactResponse.GetDefault(config.ServiceProvider.Id);

            response.StatusCode   = Saml20Constants.StatusCodes.Success;
            response.InResponseTo = artifactResolve.Id;
            response.SamlElement  = samlDoc; //samlDoc.DocumentElement;

            var responseDoc = response.GetXml();

            if (responseDoc.FirstChild is XmlDeclaration)
            {
                responseDoc.RemoveChild(responseDoc.FirstChild);
            }

            XmlSignatureUtils.SignDocument(responseDoc, response.Id, config);

            _logger.LogDebug(TraceMessages.ArtifactResolveResponseSent, artifactResolve.Artifact, responseDoc.OuterXml);

            sendResponseMessage(responseDoc.OuterXml);
        }
        /// <summary>
        /// Handles responses to an artifact resolve message.
        /// </summary>
        /// <param name="artifactResolve">The artifact resolve message.</param>
        public void RespondToArtifactResolve(ArtifactResolve artifactResolve)
        {
            var samlDoc = (XmlDocument)Context.Cache.Get(artifactResolve.Artifact);

            var response = Saml20ArtifactResponse.GetDefault(config.ServiceProvider.Id);

            response.StatusCode   = Saml20Constants.StatusCodes.Success;
            response.InResponseTo = artifactResolve.Id;
            response.SamlElement  = samlDoc.DocumentElement;

            var responseDoc = response.GetXml();

            if (responseDoc.FirstChild is XmlDeclaration)
            {
                responseDoc.RemoveChild(responseDoc.FirstChild);
            }

            XmlSignatureUtils.SignDocument(responseDoc, response.Id, config.ServiceProvider.SigningCertificate);

            Logger.DebugFormat(TraceMessages.ArtifactResolveResponseSent, artifactResolve.Artifact, responseDoc.OuterXml);

            SendResponseMessage(responseDoc.OuterXml);
        }
Exemple #20
0
        protected Saml2Request UnbindInternal(HttpRequestBase request, ArtifactResolve saml2RequestResponse, string messageName, X509Certificate2 signatureValidationCertificate)
        {
            base.UnbindInternal(request, saml2RequestResponse, signatureValidationCertificate);

            if (!"GET".Equals(request.HttpMethod, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new InvalidSaml2BindingException("Not HTTP POST Method.");
            }

            if (!request.QueryString.AllKeys.Contains(messageName))
            {
                throw new Saml2BindingException("QueryString does not contain " + messageName);
            }

            if (request.QueryString.AllKeys.Contains(Saml2Constants.Message.RelayState))
            {
                RelayState = request.QueryString[Saml2Constants.Message.RelayState];
            }

            saml2RequestResponse.Artifact = request.QueryString[messageName];

            return(saml2RequestResponse);
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                // Create a new Artifact Resolve from the request stream.
                ArtifactResolve artifactResolve = ArtifactResolve.Create(Request);

                // Get the ArtifactType0004.
                Saml2ArtifactType0004 httpArtifact = new Saml2ArtifactType0004(artifactResolve.Artifact.ArtifactValue);

                // Remove the saved http artifact from the cache.
                XmlElement samlResponseXml = (XmlElement)SamlSettings.CacheProvider.Remove(httpArtifact.ToString());

                if (samlResponseXml == null)
                {
                    throw new ApplicationException("Invalid artifact.");
                }

                // Create an ArtifactResponse.
                ArtifactResponse artifactResponse = new ArtifactResponse();
                Uri uri = new Uri(Request.Url, ResolveUrl("~/"));

                artifactResponse.Issuer = new Issuer(uri.ToString());
                // Add the SAML response XML to the artifact response.
                artifactResponse.Message = samlResponseXml;

                // Send the artifact response.
                artifactResponse.Send(Response);
            }

            catch (Exception exception)
            {
                Trace.Write("IdentityProvider", "An Error occurred", exception);
            }
        }
 public Saml2Request Unbind(HttpRequestBase request, ArtifactResolve saml2Request, X509Certificate2 signatureValidationCertificate)
 {
     return UnbindInternal(request, saml2Request, Saml2Constants.Message.SamlArt, signatureValidationCertificate);
 }
Exemple #23
0
 public Saml2Request Unbind(HttpRequestBase request, ArtifactResolve saml2Request, X509Certificate2 signatureValidationCertificate)
 {
     return(UnbindInternal(request, saml2Request, Saml2Constants.Message.SamlArt, signatureValidationCertificate));
 }
Exemple #24
0
        // Receive the authentication request and relay state.
        private void ReceiveAuthnRequest(out AuthnRequest authnRequest, out string relayState)
        {
            // Rather than separate endpoints per binding, we have a single endpoint and use a query string
            // parameter to determine the service provider to identity provider binding type.
            string bindingType = Request.QueryString[bindingQueryParameter];

            Trace.Write("IdP", "Receiving authentication request over binding " + bindingType);

            X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SPX509Certificate];
            XmlElement       authnRequestXml = null;

            switch (bindingType)
            {
            case BindingTypes.Redirect:
                bool signed = false;

                IdentityProvider.ReceiveAuthnRequestByHTTPRedirect(Request, out authnRequestXml, out relayState, out signed, x509Certificate.PublicKey.Key);
                break;

            case BindingTypes.Post:
                IdentityProvider.ReceiveAuthnRequestByHTTPPost(Request, out authnRequestXml, out relayState);
                break;

            case BindingTypes.Artifact:
                // Receive the artifact.
                HTTPArtifact httpArtifact = null;

                IdentityProvider.ReceiveArtifactByHTTPArtifact(Request, false, out httpArtifact, out relayState);

                // Create an artifact resolve request.
                ArtifactResolve artifactResolve = new ArtifactResolve();
                artifactResolve.Issuer   = new Issuer(CreateAbsoluteURL("~/"));
                artifactResolve.Artifact = new Artifact(httpArtifact.ToString());

                XmlElement artifactResolveXml = artifactResolve.ToXml();

                // Send the artifact resolve request and receive the artifact response.
                XmlElement artifactResponseXml = ArtifactResolver.SendRequestReceiveResponse(Configuration.ArtifactResolutionServiceURL, artifactResolveXml);

                ArtifactResponse artifactResponse = new ArtifactResponse(artifactResponseXml);

                // Extract the authentication request from the artifact response.
                authnRequestXml = artifactResponse.SAMLMessage;
                break;

            default:
                throw new ArgumentException("Invalid binding type");
            }

            if (SAMLMessageSignature.IsSigned(authnRequestXml))
            {
                Trace.Write("IdP", "Verifying request signature");

                if (!SAMLMessageSignature.Verify(authnRequestXml, x509Certificate))
                {
                    throw new ArgumentException("The authentication request signature failed to verify.");
                }
            }

            authnRequest = new AuthnRequest(authnRequestXml);

            Trace.Write("IdP", "Received authentication request");
        }
        // Receive the SAML response from the identity provider.
        private void ReceiveSAMLResponse(out SAMLResponse samlResponse, out string relayState)
        {
            // Rather than separate endpoints per binding, we have a single endpoint and use a query string
            // parameter to determine the identity provider to service provider binding type.
            string bindingType = Request.QueryString[bindingQueryParameter];

            Trace.Write("SP", "Receiving SAML response over binding " + bindingType);

            // Receive the SAML response over the specified binding.
            XmlElement samlResponseXml = null;

            switch (bindingType) {
                case BindingTypes.Post:
                    ServiceProvider.ReceiveSAMLResponseByHTTPPost(Request, out samlResponseXml, out relayState);
                    break;

                case BindingTypes.Artifact:
                    // Receive the artifact.
                    HTTPArtifact httpArtifact = null;

                    ServiceProvider.ReceiveArtifactByHTTPArtifact(Request, false, out httpArtifact, out relayState);

                    // Create an artifact resolve request.
                    ArtifactResolve artifactResolve = new ArtifactResolve();
                    artifactResolve.Issuer = new Issuer(CreateAbsoluteURL("~/"));
                    artifactResolve.Artifact = new Artifact(httpArtifact.ToString());

                    XmlElement artifactResolveXml = artifactResolve.ToXml();

                    // Send the artifact resolve request and receive the artifact response.
                    XmlElement artifactResponseXml = ArtifactResolver.SendRequestReceiveResponse(Configuration.ArtifactResolutionServiceURL, artifactResolveXml);

                    ArtifactResponse artifactResponse = new ArtifactResponse(artifactResponseXml);

                    // Extract the authentication request from the artifact response.
                    samlResponseXml = artifactResponse.SAMLMessage;
                    break;

                default:
                    throw new ArgumentException("Unknown binding type");
            }

            // Verify the response's signature.
            if (SAMLMessageSignature.IsSigned(samlResponseXml)) {
                Trace.Write("SP", "Verifying response signature");
                X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.IdPX509Certificate];

                if (!SAMLMessageSignature.Verify(samlResponseXml, x509Certificate)) {
                    throw new ArgumentException("The SAML response signature failed to verify.");
                }
            }

            // Deserialize the XML.
            samlResponse = new SAMLResponse(samlResponseXml);

            Trace.Write("SP", "Received SAML response");
        }
Exemple #26
0
        // Receive the authentication request from the service provider.
        private void ReceiveAuthnRequest(out AuthnRequest authnRequest, out string relayState)
        {
            // Determine the service provider to identity provider binding type.
            // We use a query string parameter rather than having separate endpoints per binding.
            string bindingType = Request.QueryString[bindingQueryParameter];

            Trace.Write("IdP", "Receiving authentication request over binding " + bindingType);

            // Receive the authentication request.
            XmlElement authnRequestXml = null;

            switch (bindingType) {
                case SAMLIdentifiers.BindingURIs.HTTPRedirect:
                    bool signed = false;
                    X509Certificate2 x509Certificate = (X509Certificate2) Application[Global.SPX509Certificate];

                    IdentityProvider.ReceiveAuthnRequestByHTTPRedirect(Request, out authnRequestXml, out relayState, out signed, x509Certificate.PublicKey.Key);
                    break;

                case SAMLIdentifiers.BindingURIs.HTTPPost:
                    IdentityProvider.ReceiveAuthnRequestByHTTPPost(Request, out authnRequestXml, out relayState);
                    break;

                case SAMLIdentifiers.BindingURIs.HTTPArtifact:
                    // Receive the artifact.
                    HTTPArtifact httpArtifact = null;

                    IdentityProvider.ReceiveArtifactByHTTPArtifact(Request, false, out httpArtifact, out relayState);

                    // Create an artifact resolve request.
                    ArtifactResolve artifactResolve = new ArtifactResolve();
                    artifactResolve.Issuer = new Issuer(CreateAbsoluteURL("~/"));
                    artifactResolve.Artifact = new Artifact(httpArtifact.ToString());

                    XmlElement artifactResolveXml = artifactResolve.ToXml();

                    // Send the artifact resolve request and receive the artifact response.
                    string spArtifactResponderURL = WebConfigurationManager.AppSettings["spArtifactResponderURL"];

                    XmlElement artifactResponseXml = ArtifactResolver.SendRequestReceiveResponse(spArtifactResponderURL, artifactResolveXml);

                    ArtifactResponse artifactResponse = new ArtifactResponse(artifactResponseXml);

                    // Extract the authentication request from the artifact response.
                    authnRequestXml = artifactResponse.SAMLMessage;
                    break;

                default:
                    throw new ArgumentException("Invalid service provider to identity provider binding");
            }

            // If using HTTP redirect the message isn't signed as the generated query string is too long for most browsers.
            if (bindingType != SAMLIdentifiers.BindingURIs.HTTPRedirect) {
                if (SAMLMessageSignature.IsSigned(authnRequestXml)) {
                    // Verify the request's signature.
                    X509Certificate2 x509Certificate = (X509Certificate2) Application[Global.SPX509Certificate];

                    if (!SAMLMessageSignature.Verify(authnRequestXml, x509Certificate)) {
                        throw new ArgumentException("The authentication request signature failed to verify.");
                    }
                }
            }

            // Deserialize the XML.
            authnRequest = new AuthnRequest(authnRequestXml);

            Trace.Write("IdP", "Received authentication request");
        }
Exemple #27
0
        // Receive the authentication request and relay state.
        private void ReceiveAuthnRequest(out AuthnRequest authnRequest, out string relayState)
        {
            // Rather than separate endpoints per binding, we have a single endpoint and use a query string
            // parameter to determine the service provider to identity provider binding type.
            string bindingType = Request.QueryString[bindingQueryParameter];

            Trace.Write("IdP", "Receiving authentication request over binding " + bindingType);

            X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SPX509Certificate];
            XmlElement authnRequestXml = null;

            switch (bindingType) {
                case BindingTypes.Redirect:
                    bool signed = false;

                    IdentityProvider.ReceiveAuthnRequestByHTTPRedirect(Request, out authnRequestXml, out relayState, out signed, x509Certificate.PublicKey.Key);
                    break;

                case BindingTypes.Post:
                    IdentityProvider.ReceiveAuthnRequestByHTTPPost(Request, out authnRequestXml, out relayState);
                    break;

                case BindingTypes.Artifact:
                    // Receive the artifact.
                    HTTPArtifact httpArtifact = null;

                    IdentityProvider.ReceiveArtifactByHTTPArtifact(Request, false, out httpArtifact, out relayState);

                    // Create an artifact resolve request.
                    ArtifactResolve artifactResolve = new ArtifactResolve();
                    artifactResolve.Issuer = new Issuer(CreateAbsoluteURL("~/"));
                    artifactResolve.Artifact = new Artifact(httpArtifact.ToString());

                    XmlElement artifactResolveXml = artifactResolve.ToXml();

                    // Send the artifact resolve request and receive the artifact response.
                    XmlElement artifactResponseXml = ArtifactResolver.SendRequestReceiveResponse(Configuration.ArtifactResolutionServiceURL, artifactResolveXml);

                    ArtifactResponse artifactResponse = new ArtifactResponse(artifactResponseXml);

                    // Extract the authentication request from the artifact response.
                    authnRequestXml = artifactResponse.SAMLMessage;
                    break;

                default:
                    throw new ArgumentException("Invalid binding type");
            }

            if (SAMLMessageSignature.IsSigned(authnRequestXml)) {
                Trace.Write("IdP", "Verifying request signature");

                if (!SAMLMessageSignature.Verify(authnRequestXml, x509Certificate)) {
                    throw new ArgumentException("The authentication request signature failed to verify.");
                }
            }

            authnRequest = new AuthnRequest(authnRequestXml);

            Trace.Write("IdP", "Received authentication request");
        }
        // Receive the authentication request from the service provider.
        public static void ReceiveAuthnRequest(Page page, out AuthnRequest authnRequest, out string relayState)
        {
            // Determine the service provider to identity provider binding type.
            // We use a query string parameter rather than having separate endpoints per binding.
            string bindingType = page.Request.QueryString[BindingQueryParameter];

            switch (bindingType)
            {
            case SamlBindingUri.HttpRedirect:
                X509Certificate2 x509Certificate = (X509Certificate2)page.Application[Global.SPCertKey];

                authnRequest = AuthnRequest.Create(page.Request.RawUrl, x509Certificate.PublicKey.Key);
                relayState   = authnRequest.RelayState;
                break;

            case SamlBindingUri.HttpPost:
                authnRequest = AuthnRequest.CreateFromHttpPost(page.Request);
                relayState   = authnRequest.RelayState;
                break;

            case SamlBindingUri.HttpArtifact:
                // Receive the artifact.
                Saml2ArtifactType0004 httpArtifact = Saml2ArtifactType0004.CreateFromHttpArtifactQueryString(page.Request);

                // Create an artifact resolve request.
                ArtifactResolve artifactResolve = new ArtifactResolve();
                artifactResolve.Issuer   = new Issuer(Util.GetAbsoluteUrl(page, "~/"));
                artifactResolve.Artifact = new Artifact(httpArtifact.ToString());

                // Look up for the appropriate artifact SP url
                string referer = page.Request.UrlReferrer.AbsoluteUri;
                int    i;
                for (i = 0; i < Services.AllowedServiceUrls.Length; i++)
                {
                    string url = Services.AllowedServiceUrls[i];

                    if (referer.StartsWith(url))
                    {
                        break;
                    }
                }

                if (i == Services.AllowedServiceUrls.Length)
                {
                    throw new Exception("Your SP is not allowed");
                }

                // Send the artifact resolve request and receive the artifact response.
                string artifactServiceProviderUrl = Services.ArtifactServiceProviderUrls[i];

                ArtifactResponse artifactResponse = ArtifactResponse.SendSamlMessageReceiveAftifactResponse(artifactServiceProviderUrl, artifactResolve);

                // Extract the authentication request from the artifact response.
                authnRequest = new AuthnRequest(artifactResponse.Message);
                relayState   = httpArtifact.RelayState;
                break;

            default:
                Trace.Write("IdentityProvider", "Invalid service provider to identity provider binding");
                authnRequest = null;
                relayState   = null;
                return;
            }

            // If using HTTP redirect the message isn't signed as the generated query string is too long for most browsers.
            if (bindingType != SamlBindingUri.HttpRedirect)
            {
                if (authnRequest.IsSigned())
                {
                    // Verify the request's signature.
                    X509Certificate2 x509Certificate = (X509Certificate2)page.Application[Global.SPCertKey];

                    if (!authnRequest.Validate(x509Certificate))
                    {
                        throw new ApplicationException("The authentication request signature failed to verify.");
                    }
                }
            }
        }
        // Receive the authentication request from the service provider.
        private void ReceiveAuthnRequest(out AuthnRequest authnRequest, out string relayState)
        {
            // Determine the service provider to identity provider binding type.
            // We use a query string parameter rather than having separate endpoints per binding.
            string bindingType = Request.QueryString[bindingQueryParameter];

            Trace.Write("IdP", "Receiving authentication request over binding " + bindingType);

            // Receive the authentication request.
            XmlElement authnRequestXml = null;

            switch (bindingType)
            {
            case SAMLIdentifiers.BindingURIs.HTTPRedirect:
                bool             signed          = false;
                X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SPX509Certificate];

                IdentityProvider.ReceiveAuthnRequestByHTTPRedirect(Request, out authnRequestXml, out relayState, out signed, x509Certificate.PublicKey.Key);
                break;

            case SAMLIdentifiers.BindingURIs.HTTPPost:
                IdentityProvider.ReceiveAuthnRequestByHTTPPost(Request, out authnRequestXml, out relayState);
                break;

            case SAMLIdentifiers.BindingURIs.HTTPArtifact:
                // Receive the artifact.
                HTTPArtifact httpArtifact = null;

                IdentityProvider.ReceiveArtifactByHTTPArtifact(Request, false, out httpArtifact, out relayState);

                // Create an artifact resolve request.
                ArtifactResolve artifactResolve = new ArtifactResolve();
                artifactResolve.Issuer   = new Issuer(CreateAbsoluteURL("~/"));
                artifactResolve.Artifact = new Artifact(httpArtifact.ToString());

                XmlElement artifactResolveXml = artifactResolve.ToXml();

                // Send the artifact resolve request and receive the artifact response.
                string spArtifactResponderURL = WebConfigurationManager.AppSettings["spArtifactResponderURL"];

                XmlElement artifactResponseXml = ArtifactResolver.SendRequestReceiveResponse(spArtifactResponderURL, artifactResolveXml);

                ArtifactResponse artifactResponse = new ArtifactResponse(artifactResponseXml);

                // Extract the authentication request from the artifact response.
                authnRequestXml = artifactResponse.SAMLMessage;
                break;

            default:
                throw new ArgumentException("Invalid service provider to identity provider binding");
            }

            // If using HTTP redirect the message isn't signed as the generated query string is too long for most browsers.
            if (bindingType != SAMLIdentifiers.BindingURIs.HTTPRedirect)
            {
                if (SAMLMessageSignature.IsSigned(authnRequestXml))
                {
                    // Verify the request's signature.
                    X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SPX509Certificate];

                    if (!SAMLMessageSignature.Verify(authnRequestXml, x509Certificate))
                    {
                        throw new ArgumentException("The authentication request signature failed to verify.");
                    }
                }
            }

            // Deserialize the XML.
            authnRequest = new AuthnRequest(authnRequestXml);

            Trace.Write("IdP", "Received authentication request");
        }