Пример #1
0
        /// <summary>
        /// Processes a successful SAML response and redirect to the requested URL.
        /// </summary>
        /// <param name="page">The page object.</param>
        /// <param name="samlResponse">The SAML response object.</param>
        /// <param name="relayState">The relay state.</param>
        public static void SamlSuccessRedirect(Page page, ComponentPro.Saml2.Response samlResponse, string relayState)
        {
            // Get the previously loaded certificate.
            X509Certificate2 x509Certificate = (X509Certificate2)page.Application[Global.SpCertKey];

            Assertion samlAssertion;

            // Check assertions.
            if (samlResponse.GetAssertions().Count > 0)
            {
                // Extract the first assertion.
                samlAssertion = samlResponse.GetAssertions()[0];
            }
            else if (samlResponse.GetEncryptedAssertions().Count > 0)
            {
                // Extract the first assertion.
                samlAssertion = samlResponse.GetEncryptedAssertions()[0].Decrypt(x509Certificate.PrivateKey, null);
            }
            else
            {
                throw new ApplicationException("No assertions in response");
            }

            string userName;

            // Get the subject name identifier.
            if (samlAssertion.Subject.NameId != null)
            {
                userName = samlAssertion.Subject.NameId.NameIdentifier;
            }
            else if (samlAssertion.Subject.EncryptedId != null)
            {
                NameId nameId = samlAssertion.Subject.EncryptedId.Decrypt(x509Certificate.PrivateKey, null);
                userName = nameId.NameIdentifier;
            }
            else
            {
                throw new ApplicationException("No name in subject");
            }

            // Get the originally requested resource URL from the relay state.
            string resourceUrl = (string)SamlSettings.CacheProvider.Remove(relayState);

            if (resourceUrl == null)
            {
                throw new ApplicationException("Invalid relay state");
            }

            // Create a login context for the asserted identity.
            FormsAuthentication.SetAuthCookie(userName, false);

            // Redirect to the originally requested resource URL.
            page.Response.Redirect(resourceUrl, false);
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                #region Receive SAML Response

                // Create a SAML response from the HTTP request.
                ComponentPro.Saml2.Response samlResponse = ComponentPro.Saml2.Response.Create(Request);

                // Is it signed?
                if (samlResponse.IsSigned())
                {
                    // Loaded the previously loaded certificate.
                    X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.CertKeyName];

                    // Validate the SAML response with the certificate.
                    if (!samlResponse.Validate(x509Certificate))
                    {
                        throw new ApplicationException("SAML response signature is not valid.");
                    }
                }

                #endregion

                #region Process the response

                // Success?
                if (!samlResponse.IsSuccess())
                {
                    throw new ApplicationException("SAML response is not success");
                }

                Assertion samlAssertion;

                // Define ENCRYPTEDSAML preprocessor flag if you wish to decrypt the SAML response.
#if ENCRYPTEDSAML
                if (samlResponse.GetEncryptedAssertions().Count > 0)
                {
                    EncryptedAssertion encryptedAssertion = samlResponse.GetEncryptedAssertions()[0];

                    // Load the private key.
                    // Consider caching the loaded key in production environment for better performance.
                    X509Certificate2 decryptionKey = new X509Certificate2(Path.Combine(HttpRuntime.AppDomainAppPath, "EncryptionKey.pfx"), "password");

                    // Decrypt the encrypted assertion.
                    samlAssertion = encryptedAssertion.Decrypt(decryptionKey.PrivateKey, null);
                }
                else
                {
                    throw new ApplicationException("No encrypted assertions found in the SAML response");
                }
#else
                // Get the asserted identity.
                if (samlResponse.GetAssertions().Count > 0)
                {
                    samlAssertion = samlResponse.GetAssertions()[0];
                }
                else
                {
                    throw new ApplicationException("No assertions found in the SAML response");
                }
#endif

                // Get the subject name identifier.
                string userName;

                if (samlAssertion.Subject.NameId != null)
                {
                    userName = samlAssertion.Subject.NameId.NameIdentifier;
                }
                else
                {
                    throw new ApplicationException("Name identifier not found in subject");
                }

                #region Extract Custom Attributes

                // If you need to add custom attributes, uncomment the following code
                //if (samlAssertion.AttributeStatements.Count > 0)
                //{
                //    foreach (AttributeStatement attributeStatement in samlAssertion.AttributeStatements)
                //    {
                //        // If you need to decrypt encrypted attributes, refer to this topic: http://www.samlcomponent.net/encrypting-and-decrypting-saml-response-xml
                //        foreach (ComponentPro.Saml2.Attribute attribute in attributeStatement.Attributes)
                //        {
                //            // Process your custom attribute here.
                //            // ...
                //        }
                //    }
                //}

                #endregion

                // Set authentication cookie.
                FormsAuthentication.SetAuthCookie(userName, false);

                // Redirect to the requested URL.
                Response.Redirect(samlResponse.RelayState, false);

                #endregion
            }

            catch (Exception exception)
            {
                Trace.Write("ServiceProvider", "An Error occurred", exception);
            }
        }
Пример #3
0
        /// <summary>
        /// Processes a successful SAML response and redirect to the requested URL.
        /// </summary>
        /// <param name="page">The page object.</param>
        /// <param name="samlResponse">The SAML response object.</param>
        /// <param name="relayState">The relay state.</param>
        public static void SamlSuccessRedirect(Page page, ComponentPro.Saml2.Response samlResponse, string relayState)
        {
            // Get the previously loaded certificate.
            X509Certificate2 x509Certificate = (X509Certificate2)page.Application[Global.SpCertKey];

            Assertion samlAssertion;

            // Check assertions.
            if (samlResponse.GetAssertions().Count > 0)
            {
                // Extract the first assertion.
                samlAssertion = samlResponse.GetAssertions()[0];
            }
            else if (samlResponse.GetEncryptedAssertions().Count > 0)
            {
                // Extract the first assertion.
                samlAssertion = samlResponse.GetEncryptedAssertions()[0].Decrypt(x509Certificate.PrivateKey, null);
            }
            else
            {
                throw new ApplicationException("No assertions in response");
            }

            string userName;

            // Get the subject name identifier.
            if (samlAssertion.Subject.NameId != null)
            {
                //userName = samlAssertion.Subject.NameId.NameIdentifier;
                userName = samlAssertion.GetAttributeValueByFriendlyName("eduPersonPrincipalName");

                System.Collections.Generic.Dictionary<string, string> dict = new System.Collections.Generic.Dictionary<string, string>();

                foreach (ComponentPro.Saml2.Attribute attribute in samlAssertion.AttributeStatements[0].Attributes)
                {
                    dict.Add(attribute.FriendlyName, attribute.Values[0].ToString());
                    System.Diagnostics.Trace.WriteLine(attribute.FriendlyName + ":" + attribute.Values[0].ToString());
                }
                HttpContext.Current.Session.Add("samlAttributes", dict);
            }
            else if (samlAssertion.Subject.EncryptedId != null)
            {
                NameId nameId = samlAssertion.Subject.EncryptedId.Decrypt(x509Certificate.PrivateKey, null);
                userName = nameId.NameIdentifier;
            }
            else
            {
                throw new ApplicationException("No name in subject");
            }


            try
            {
                string aaURL = "https://idp.testshib.org:8443/idp/profile/SAML2/SOAP/AttributeQuery";
                //Testing subject
                NameId subje = new NameId(userName,null,null,SamlNameIdentifierFormat.Unspecified,aaURL);
                
                //Testing subject
                Subject subject = new Subject(new NameId(userName));
                SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SamlSubjectConfirmationMethod.Bearer);
                SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();
                subjectConfirmationData.Recipient = aaURL;
                subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
                subject.SubjectConfirmations.Add(subjectConfirmation);

                AttributeQuery attributeQuery = new AttributeQuery();
                //attributeQuery.Subject = subject;
                attributeQuery.Destination = aaURL;
                attributeQuery.Issuer = new Issuer(Global.entityId);
                attributeQuery.Attributes.Add(new ComponentPro.Saml2.Attribute() { FriendlyName = "givenName" });
                attributeQuery.Subject = new Subject(samlAssertion.Subject.NameId);
                
                
                attributeQuery.Sign(x509Certificate);
                System.Diagnostics.Trace.WriteLine("Trying to get attributes from AA");
                System.Diagnostics.Trace.WriteLine("AA query " + attributeQuery.GetXml().OuterXml);
                System.Diagnostics.Trace.WriteLine("AA Subject " + attributeQuery.Subject.ToString());

                ArtifactResponse artifactResponse = ArtifactResponse.SendSamlMessageReceiveAftifactResponse(aaURL, attributeQuery);

                Response attrResponse;
                attrResponse = new ComponentPro.Saml2.Response(artifactResponse.Message);
                System.Diagnostics.Trace.WriteLine("AA reponse " + attrResponse.GetXml().OuterXml);

            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.WriteLine("Execption: " + e.ToString());
                //throw;
            }
            // Get the originally requested resource URL from the relay state.
            string resourceUrl = (string)SamlSettings.CacheProvider.Remove(relayState);
            if (resourceUrl == null)
            {
                throw new ApplicationException("Invalid relay state");
            }

            // Create a login context for the asserted identity.
            FormsAuthentication.SetAuthCookie(userName, false);
            

            // Redirect to the originally requested resource URL.
            page.Response.Redirect(resourceUrl, false);
        }