コード例 #1
1
ファイル: SSOService.aspx.cs プロジェクト: HRINY/HRI-Umbraco
        // Create a SAML response with the user's local identity, if any, or indicating an error.
        private SAMLResponse CreateSAMLResponse(SSOState ssoState)
        {
            Trace.Write("IdP", "Creating SAML response");

            SAMLResponse samlResponse = new SAMLResponse();
            string issuerURL = CreateAbsoluteURL("~/");
            Issuer issuer = new Issuer(issuerURL);
            samlResponse.Issuer = issuer;

            if (User.Identity.IsAuthenticated) {
                samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);

                SAMLAssertion samlAssertion = new SAMLAssertion();
                samlAssertion.Issuer = issuer;

                Subject subject = new Subject(new NameID(User.Identity.Name));
                SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
                SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();
                subjectConfirmationData.InResponseTo = ssoState.authnRequest.ID;
                subjectConfirmationData.Recipient = ssoState.assertionConsumerServiceURL;
                subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
                subject.SubjectConfirmations.Add(subjectConfirmation);
                samlAssertion.Subject = subject;

                AuthnStatement authnStatement = new AuthnStatement();
                authnStatement.AuthnContext = new AuthnContext();
                authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Password);
                samlAssertion.Statements.Add(authnStatement);

                // Attributes may be included in the SAML assertion.
                AttributeStatement attributeStatement = new AttributeStatement();
                attributeStatement.Attributes.Add(new SAMLAttribute("Membership", SAMLIdentifiers.AttributeNameFormats.Basic, null, "Gold"));
                samlAssertion.Statements.Add(attributeStatement);

                samlResponse.Assertions.Add(samlAssertion);
            } else {
                samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Responder, SAMLIdentifiers.SecondaryStatusCodes.AuthnFailed, "The user is not authenticated at the identity provider");
            }

            Trace.Write("IdP", "Created SAML response");

            return samlResponse;
        }
コード例 #2
0
ファイル: SSOService.aspx.cs プロジェクト: HRINY/HRI-Umbraco
        // Create a SAML response with the user's local identity.
        private SAMLResponse CreateSAMLResponse()
        {
            Trace.Write("IdP", "Creating SAML response");

            SAMLResponse samlResponse = new SAMLResponse();
            samlResponse.Destination = Configuration.AssertionConsumerServiceURL;
            Issuer issuer = new Issuer(CreateAbsoluteURL("~/"));
            samlResponse.Issuer = issuer;
            samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);

            SAMLAssertion samlAssertion = new SAMLAssertion();
            samlAssertion.Issuer = issuer;

            Subject subject = new Subject(new NameID(User.Identity.Name));
            SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
            SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();
            subjectConfirmationData.Recipient = Configuration.AssertionConsumerServiceURL;
            subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
            subject.SubjectConfirmations.Add(subjectConfirmation);
            samlAssertion.Subject = subject;

            AuthnStatement authnStatement = new AuthnStatement();
            authnStatement.AuthnContext = new AuthnContext();
            authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Password);
            samlAssertion.Statements.Add(authnStatement);

            samlResponse.Assertions.Add(samlAssertion);

            Trace.Write("IdP", "Created SAML response");

            return samlResponse;
        }
コード例 #3
0
        private static void VerifyMessage(XmlElement xmlElement)
        {
            Console.Error.WriteLine("Verifying SAML message");

            try
            {
                if (SAMLMessageSignature.IsSigned(xmlElement))
                {
                    bool verified = SAMLMessageSignature.Verify(xmlElement, x509Certificate);
                    Console.Error.WriteLine("Verified: " + verified);
                }
                else
                {
                    Console.Error.WriteLine("The SAML message isn't signed");
                }
            }

            catch (Exception exception)
            {
                Console.Error.WriteLine(exception.ToString());
            }

            foreach (XmlElement assertionElement in SAMLAssertion.Find(xmlElement))
            {
                VerifyAssertion(assertionElement);
            }
        }
コード例 #4
0
        // Process a successful SAML response.
        private void ProcessSuccessSAMLResponse(SAMLResponse samlResponse, string relayState)
        {
            Trace.Write("SP", "Processing successful SAML response");

            // Extract the asserted identity from the SAML response.
            SAMLAssertion samlAssertion = (SAMLAssertion)samlResponse.Assertions[0];

            // Get the subject name identifier.
            string userName = samlAssertion.Subject.NameID.NameIdentifier;

            // Get the originally requested resource URL from the relay state.
            RelayState cachedRelayState = RelayStateCache.Remove(relayState);

            if (cachedRelayState == null)
            {
                Trace.Write("SP", "Nothing in cache");

                return;
            }

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

            // Redirect to the originally requested resource URL.
            Response.Redirect(cachedRelayState.ResourceURL, false);

            Trace.Write("SP", "Processed successful SAML response");
        }
コード例 #5
0
        // Process a successful SAML response.
        private void ProcessSuccessSAMLResponse(SAMLResponse samlResponse, string relayState)
        {
            Trace.Write("SP", "Processing successful SAML response");

            // Load the decryption key.
            X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SPX509Certificate];

            // Extract the asserted identity from the SAML response.
            SAMLAssertion samlAssertion = null;

            if (samlResponse.GetUnsignedAssertions().Count > 0)
            {
                samlAssertion = samlResponse.GetUnsignedAssertions()[0];
            }
            else if (samlResponse.GetEncryptedAssertions().Count > 0)
            {
                Trace.Write("SP", "Decrypting assertion");
                samlAssertion = samlResponse.GetEncryptedAssertions()[0].Decrypt(x509Certificate.PrivateKey, null, null);
            }
            else
            {
                throw new ArgumentException("No assertions in response");
            }

            // Get the subject name identifier.
            string userName = null;

            if (samlAssertion.Subject.NameID != null)
            {
                userName = samlAssertion.Subject.NameID.NameIdentifier;
            }
            else if (samlAssertion.Subject.EncryptedID != null)
            {
                Trace.Write("SP", "Decrypting ID");
                NameID nameID = samlAssertion.Subject.EncryptedID.Decrypt(x509Certificate.PrivateKey, null, null);
                userName = nameID.NameIdentifier;
            }
            else
            {
                throw new ArgumentException("No name in subject");
            }

            // Get the originally requested resource URL from the relay state.
            RelayState cachedRelayState = RelayStateCache.Remove(relayState);

            if (cachedRelayState == null)
            {
                throw new ArgumentException("Invalid relay state");
            }

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

            // Redirect to the originally requested resource URL.
            Response.Redirect(cachedRelayState.ResourceURL, false);

            Trace.Write("SP", "Processed successful SAML response");
        }
コード例 #6
0
        // Create a SAML response with the user's local identity.
        private SAMLResponse CreateSAMLResponse()
        {
            Trace.Write("IdP", "Creating SAML response");

            SAMLResponse samlResponse = new SAMLResponse();

            samlResponse.Destination = Configuration.AssertionConsumerServiceURL;
            Issuer issuer = new Issuer(Configuration.Issuer);

            samlResponse.Issuer = issuer;
            samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);

            SAMLAssertion samlAssertion = new SAMLAssertion();

            samlAssertion.Issuer = issuer;

            // For simplicity, a configured Salesforce user name is used.
            // NB. You must update the web.config to specify a valid Salesforce user name.
            // In a real world application you would perform some sort of local to Salesforce identity mapping.
            Subject                 subject                 = new Subject(new NameID(Configuration.SalesforceLoginID, null, null, SAMLIdentifiers.NameIdentifierFormats.Unspecified, null));
            SubjectConfirmation     subjectConfirmation     = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
            SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();

            subjectConfirmationData.Recipient           = Configuration.AssertionConsumerServiceURL;
            subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
            subject.SubjectConfirmations.Add(subjectConfirmation);
            samlAssertion.Subject = subject;

            Conditions          conditions          = new Conditions(new TimeSpan(1, 0, 0));
            AudienceRestriction audienceRestriction = new AudienceRestriction();

            audienceRestriction.Audiences.Add(new Audience(audienceURI));
            conditions.ConditionsList.Add(audienceRestriction);
            samlAssertion.Conditions = conditions;

            subjectConfirmationData.NotOnOrAfter = conditions.NotOnOrAfter;

            AuthnStatement authnStatement = new AuthnStatement();

            authnStatement.AuthnContext = new AuthnContext();
            authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Unspecified);
            samlAssertion.Statements.Add(authnStatement);

            AttributeStatement attributeStatement = new AttributeStatement();

            attributeStatement.Attributes.Add(new SAMLAttribute(AttributeNames.SSOStartPage, SAMLIdentifiers.AttributeNameFormats.Unspecified, null, CreateAbsoluteURL("~/Login.aspx")));
            attributeStatement.Attributes.Add(new SAMLAttribute(AttributeNames.LogoutURL, SAMLIdentifiers.AttributeNameFormats.Unspecified, null, CreateAbsoluteURL("~/Logout.aspx")));
            samlAssertion.Statements.Add(attributeStatement);

            samlResponse.Assertions.Add(samlAssertion);

            Trace.Write("IdP", "Created SAML response");

            return(samlResponse);
        }
コード例 #7
0
        // Create a SAML response with the user's local identity, if any, or indicating an error.
        private SAMLResponse CreateSAMLResponse(AuthnRequest authnRequest)
        {
            Trace.Write("IdP", "Creating SAML response");

            SAMLResponse samlResponse = new SAMLResponse();

            samlResponse.InResponseTo = authnRequest.ID;
            samlResponse.Destination  = authnRequest.AssertionConsumerServiceURL;
            Issuer issuer = new Issuer(CreateAbsoluteURL("~/"));

            samlResponse.Issuer = issuer;

            if (User.Identity.IsAuthenticated)
            {
                samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);

                SAMLAssertion samlAssertion = new SAMLAssertion();
                samlAssertion.Issuer = issuer;

                samlAssertion.Conditions = new Conditions(new TimeSpan(0, 10, 0));
                AudienceRestriction audienceRestriction = new AudienceRestriction();
                audienceRestriction.Audiences.Add(new Audience(authnRequest.AssertionConsumerServiceURL));
                samlAssertion.Conditions.ConditionsList.Add(audienceRestriction);

                Subject                 subject                 = new Subject(new NameID(User.Identity.Name));
                SubjectConfirmation     subjectConfirmation     = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
                SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();
                subjectConfirmationData.InResponseTo = authnRequest.ID;
                subjectConfirmationData.Recipient    = authnRequest.AssertionConsumerServiceURL;
                subjectConfirmationData.NotBefore    = samlAssertion.Conditions.NotBefore;
                subjectConfirmationData.NotOnOrAfter = samlAssertion.Conditions.NotOnOrAfter;

                subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
                subject.SubjectConfirmations.Add(subjectConfirmation);
                samlAssertion.Subject = subject;

                AuthnStatement authnStatement = new AuthnStatement();
                authnStatement.AuthnContext = new AuthnContext();
                authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Password);
                samlAssertion.Statements.Add(authnStatement);

                samlResponse.Assertions.Add(samlAssertion);
            }
            else
            {
                samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Responder, SAMLIdentifiers.SecondaryStatusCodes.AuthnFailed, "The user is not authenticated at the identity provider");
            }

            Trace.Write("IdP", "Created SAML response");

            return(samlResponse);
        }
コード例 #8
0
ファイル: KGSSService.cs プロジェクト: simpleidserver/medikit
        public async Task <KGSSGetKeyResponseContent> GetKeyFromKGSS(string keyId, SAMLAssertion assertion)
        {
            var orgAuthCertificate = _keyStoreManager.GetOrgAuthCertificate();
            var orgEtk             = await _etkService.GetOrgETK();

            var kgssEtk = await _etkService.GetKgssETK();

            var getKeyRequestContent = new KGSSGetKeyRequestContent
            {
                KeyIdentifier = keyId,
                ETK           = orgEtk.ETK
            };
            var contentInfoPayload       = Encoding.UTF8.GetBytes(getKeyRequestContent.Serialize().ToString());
            var sealedContentInfoPayload = TripleWrapper.Seal(contentInfoPayload, orgAuthCertificate, kgssEtk.Certificate);
            var issueInstant             = DateTime.UtcNow;
            var soapRequest = SOAPRequestBuilder <KGSSGetKeyRequestBody> .New(new KGSSGetKeyRequestBody
            {
                Id      = $"id-{Guid.NewGuid().ToString()}",
                Request = new KGSSGetKeyRequest
                {
                    SealedKeyRequest = new KGSSSealedKeyRequest
                    {
                        SealedContent = Convert.ToBase64String(sealedContentInfoPayload)
                    }
                }
            })
                              .AddTimestamp(issueInstant, issueInstant.AddHours(1))
                              .AddSAMLAssertion(assertion)
                              .AddReferenceToSAMLAssertion()
                              .SignWithCertificate(orgAuthCertificate)
                              .Build();

            var result = await _soapClient.Send(soapRequest, new Uri(_options.KgssUrl), null);

            result.EnsureSuccessStatusCode();
            var xml = await result.Content.ReadAsStringAsync();

            var response = SOAPEnvelope <KGSSGetKeyResponseBody> .Deserialize(xml);

            var certificates = new List <X509Certificate2>
            {
                orgAuthCertificate.Certificate,
                _keyStoreManager.GetOrgETKCertificate().Certificate
            };
            var unsealedPayload = TripleWrapper.Unseal(Convert.FromBase64String(response.Body.GetKeyResponse.SealedKeyResponse.SealedContent), certificates.ToCertificateCollection());

            return(KGSSGetKeyResponseContent.Deserialize(unsealedPayload));
        }
コード例 #9
0
        // Process the SAML response.
        private void ProcessSAMLResponse(SAMLResponse samlResponse, string relayState)
        {
            Trace.Write("SP", "Processing SAML response");

            // Check whether the SAML response indicates success.
            if (!samlResponse.IsSuccess())
            {
                throw new ArgumentException("Received error response");
            }

            // Extract the asserted identity from the SAML response.
            SAMLAssertion samlAssertion = null;

            if (samlResponse.GetAssertions().Count > 0)
            {
                samlAssertion = samlResponse.GetAssertions()[0];
            }
            else
            {
                throw new ArgumentException("No assertions in response");
            }

            // Enforce single use of the SAML assertion.
            if (!AssertionIDCache.Add(samlAssertion))
            {
                throw new ArgumentException("The SAML assertion has already been used");
            }

            // Get the subject name identifier.
            string userName = null;

            if (samlAssertion.Subject.NameID != null)
            {
                userName = samlAssertion.Subject.NameID.NameIdentifier;
            }
            else
            {
                throw new ArgumentException("No name in subject");
            }

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

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

            Trace.Write("SP", "Processed successful SAML response");
        }
コード例 #10
0
ファイル: SSOService.aspx.cs プロジェクト: HRINY/HRI-Umbraco
        // Create a SAML response with the user's local identity.
        private SAMLResponse CreateSAMLResponse()
        {
            Trace.Write("IdP", "Creating SAML response");

            SAMLResponse samlResponse = new SAMLResponse();
            samlResponse.Destination = Configuration.AssertionConsumerServiceURL;
            Issuer issuer = new Issuer(Configuration.Issuer);
            samlResponse.Issuer = issuer;
            samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);

            SAMLAssertion samlAssertion = new SAMLAssertion();
            samlAssertion.Issuer = issuer;

            // For simplicity, a configured Salesforce user name is used.
            // NB. You must update the web.config to specify a valid Salesforce user name.
            // In a real world application you would perform some sort of local to Salesforce identity mapping.
            Subject subject = new Subject(new NameID(Configuration.SalesforceLoginID, null, null, SAMLIdentifiers.NameIdentifierFormats.Unspecified, null));
            SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
            SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();
            subjectConfirmationData.Recipient = Configuration.AssertionConsumerServiceURL;
            subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
            subject.SubjectConfirmations.Add(subjectConfirmation);
            samlAssertion.Subject = subject;

            Conditions conditions = new Conditions(new TimeSpan(1, 0, 0));
            AudienceRestriction audienceRestriction = new AudienceRestriction();
            audienceRestriction.Audiences.Add(new Audience(audienceURI));
            conditions.ConditionsList.Add(audienceRestriction);
            samlAssertion.Conditions = conditions;

            subjectConfirmationData.NotOnOrAfter = conditions.NotOnOrAfter;

            AuthnStatement authnStatement = new AuthnStatement();
            authnStatement.AuthnContext = new AuthnContext();
            authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Unspecified);
            samlAssertion.Statements.Add(authnStatement);

            AttributeStatement attributeStatement = new AttributeStatement();
            attributeStatement.Attributes.Add(new SAMLAttribute(AttributeNames.SSOStartPage, SAMLIdentifiers.AttributeNameFormats.Unspecified, null, CreateAbsoluteURL("~/Login.aspx")));
            attributeStatement.Attributes.Add(new SAMLAttribute(AttributeNames.LogoutURL, SAMLIdentifiers.AttributeNameFormats.Unspecified, null, CreateAbsoluteURL("~/Logout.aspx")));
            samlAssertion.Statements.Add(attributeStatement);

            samlResponse.Assertions.Add(samlAssertion);

            Trace.Write("IdP", "Created SAML response");

            return samlResponse;
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: HRINY/HRI-Umbraco
        static void Main(string[] args)
        {
            try {
            #if DOTNET45
                // Register the SHA-256 cryptographic algorithm.
                // Only supported in .NET 4.5 and above.
                CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
            #endif

                // Load the certificate and private key for signature generation.
                X509Certificate2 x509Certificate = new X509Certificate2("idp.pfx", "password");

                // Create a basic SAML assertion and serialize it to XML.
                SAMLAssertion samlAssertion = new SAMLAssertion();
                samlAssertion.Issuer = new Issuer("test");
                XmlElement samlAssertionElement = samlAssertion.ToXml();

                // Sign the SAML assertion using SHA-256 for the digest and signature algorithms.
                SAMLAssertionSignature.Generate(samlAssertionElement, x509Certificate.PrivateKey, x509Certificate, null, "http://www.w3.org/2001/04/xmlenc#sha256", "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
                Console.WriteLine("Signed SAML assertion: {0}", samlAssertionElement.OuterXml);

                // Verify the signature.
                bool verified = SAMLAssertionSignature.Verify(samlAssertionElement);
                Console.WriteLine("Signature verified: {0}", verified);

                // The HTTP-redirect doesn't use XML signatures so check it separately.
                // Create a basic authn request and serialize it to XML.
                AuthnRequest authnRequest = new AuthnRequest();
                authnRequest.Issuer = new Issuer("test");
                XmlElement authnRequestElement = authnRequest.ToXml();

                // Create the HTTP-redirect URL included the SHA-256 signature.
                string url = HTTPRedirectBinding.CreateRequestRedirectURL("http://www.test.com", authnRequestElement, null, x509Certificate.PrivateKey, HTTPRedirectBinding.SignatureAlgorithms.RSA_SHA256);

                string relayState = null;
                bool signed = false;

                // Retrieve the authn request from the HTTP-redirect URL and verify the signature.
                HTTPRedirectBinding.GetRequestFromRedirectURL(url, out authnRequestElement, out relayState, out signed, x509Certificate.PublicKey.Key);
            }

            catch (Exception exception) {
                // If signature generation/verification fails then most likely the .NET CLR security update
                // hasn't been installed and configured correctly or the inbuilt .NET SHA-256 support hasn't been initialized.
                Console.WriteLine(exception.ToString());
            }
        }
コード例 #12
0
        // Create a SAML response with the user's local identity, if any, or indicating an error.
        private SAMLResponse CreateSAMLResponse(SSOState ssoState)
        {
            Trace.Write("IdP", "Creating SAML response");

            SAMLResponse samlResponse = new SAMLResponse();
            string       issuerURL    = CreateAbsoluteURL("~/");
            Issuer       issuer       = new Issuer(issuerURL);

            samlResponse.Issuer = issuer;

            if (User.Identity.IsAuthenticated)
            {
                samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);

                SAMLAssertion samlAssertion = new SAMLAssertion();
                samlAssertion.Issuer = issuer;

                Subject                 subject                 = new Subject(new NameID(User.Identity.Name));
                SubjectConfirmation     subjectConfirmation     = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
                SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();
                subjectConfirmationData.InResponseTo        = ssoState.authnRequest.ID;
                subjectConfirmationData.Recipient           = ssoState.assertionConsumerServiceURL;
                subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
                subject.SubjectConfirmations.Add(subjectConfirmation);
                samlAssertion.Subject = subject;

                AuthnStatement authnStatement = new AuthnStatement();
                authnStatement.AuthnContext = new AuthnContext();
                authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Password);
                samlAssertion.Statements.Add(authnStatement);

                // Attributes may be included in the SAML assertion.
                AttributeStatement attributeStatement = new AttributeStatement();
                attributeStatement.Attributes.Add(new SAMLAttribute("Membership", SAMLIdentifiers.AttributeNameFormats.Basic, null, "Gold"));
                samlAssertion.Statements.Add(attributeStatement);

                samlResponse.Assertions.Add(samlAssertion);
            }
            else
            {
                samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Responder, SAMLIdentifiers.SecondaryStatusCodes.AuthnFailed, "The user is not authenticated at the identity provider");
            }

            Trace.Write("IdP", "Created SAML response");

            return(samlResponse);
        }
コード例 #13
0
        static void Main(string[] args)
        {
            try {
#if DOTNET45
                // Register the SHA-256 cryptographic algorithm.
                // Only supported in .NET 4.5 and above.
                CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
#endif

                // Load the certificate and private key for signature generation.
                X509Certificate2 x509Certificate = new X509Certificate2("idp.pfx", "password");

                // Create a basic SAML assertion and serialize it to XML.
                SAMLAssertion samlAssertion = new SAMLAssertion();
                samlAssertion.Issuer = new Issuer("test");
                XmlElement samlAssertionElement = samlAssertion.ToXml();

                // Sign the SAML assertion using SHA-256 for the digest and signature algorithms.
                SAMLAssertionSignature.Generate(samlAssertionElement, x509Certificate.PrivateKey, x509Certificate, null, "http://www.w3.org/2001/04/xmlenc#sha256", "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
                Console.WriteLine("Signed SAML assertion: {0}", samlAssertionElement.OuterXml);

                // Verify the signature.
                bool verified = SAMLAssertionSignature.Verify(samlAssertionElement);
                Console.WriteLine("Signature verified: {0}", verified);

                // The HTTP-redirect doesn't use XML signatures so check it separately.
                // Create a basic authn request and serialize it to XML.
                AuthnRequest authnRequest = new AuthnRequest();
                authnRequest.Issuer = new Issuer("test");
                XmlElement authnRequestElement = authnRequest.ToXml();

                // Create the HTTP-redirect URL included the SHA-256 signature.
                string url = HTTPRedirectBinding.CreateRequestRedirectURL("http://www.test.com", authnRequestElement, null, x509Certificate.PrivateKey, HTTPRedirectBinding.SignatureAlgorithms.RSA_SHA256);

                string relayState = null;
                bool   signed     = false;

                // Retrieve the authn request from the HTTP-redirect URL and verify the signature.
                HTTPRedirectBinding.GetRequestFromRedirectURL(url, out authnRequestElement, out relayState, out signed, x509Certificate.PublicKey.Key);
            }

            catch (Exception exception) {
                // If signature generation/verification fails then most likely the .NET CLR security update
                // hasn't been installed and configured correctly or the inbuilt .NET SHA-256 support hasn't been initialized.
                Console.WriteLine(exception.ToString());
            }
        }
コード例 #14
0
        private static void SignAndVerify(X509Certificate2 x509Certificate, string digestMethod, string signatureMethod)
        {
            try
            {
                Console.WriteLine("Testing signature generation and verification using \"{0}\".", signatureMethod);

                // Create a basic SAML assertion and serialize it to XML.
                SAMLAssertion samlAssertion = new SAMLAssertion();
                samlAssertion.Issuer = new Issuer("test");
                XmlElement samlAssertionElement = samlAssertion.ToXml();

                // Sign the SAML assertion using the specified digest and signature methods.
                SAMLAssertionSignature.Generate(samlAssertionElement, x509Certificate.PrivateKey, x509Certificate, null, digestMethod, signatureMethod);

                // Verify the signature.
                bool verified = SAMLAssertionSignature.Verify(samlAssertionElement);

                if (!verified)
                {
                    throw new Exception("The XML signature failed to verify.");
                }

                // The HTTP-redirect doesn't use XML signatures so check it separately.
                // Create a basic authn request and serialize it to XML.
                AuthnRequest authnRequest = new AuthnRequest();
                authnRequest.Issuer = new Issuer("test");
                XmlElement authnRequestElement = authnRequest.ToXml();

                // Create the HTTP-redirect URL included the signature.
                string url = HTTPRedirectBinding.CreateRequestRedirectURL("http://www.test.com", authnRequestElement, null, x509Certificate.PrivateKey, signatureMethod);

                string relayState = null;
                bool   signed     = false;

                // Retrieve the authn request from the HTTP-redirect URL and verify the signature.
                HTTPRedirectBinding.GetRequestFromRedirectURL(url, out authnRequestElement, out relayState, out signed, x509Certificate.PublicKey.Key);

                Console.WriteLine("Signature generation and verification using \"{0}\" was successful.", signatureMethod);
            }

            catch (Exception exception)
            {
                Console.WriteLine("Signature generation and verification using \"{0}\" failed.", signatureMethod);
                Console.WriteLine(exception.ToString());
            }
        }
コード例 #15
0
        public async Task <bool> Handle(RevokePrescriptionCommand command, CancellationToken token)
        {
            SAMLAssertion assertion;

            try
            {
                assertion = SAMLAssertion.Deserialize(command.AssertionToken);
            }
            catch
            {
                throw new BadAssertionTokenException(Global.BadAssertionToken);
            }

            await _recipeService.RevokePrescription(command.Rid, command.Reason, assertion);

            return(true);
        }
コード例 #16
0
        public async Task <bool> Handle(DeleteMessageCommand request, CancellationToken cancellationToken)
        {
            SAMLAssertion assertion;

            try
            {
                assertion = SAMLAssertion.Deserialize(request.AssertionToken);
            }
            catch
            {
                throw new BadAssertionTokenException(Global.BadAssertionToken);
            }

            await _ehealthBoxService.DeleteMessage(new EHealthBoxDeleteMessageRequest
            {
                MessageIdLst = request.MessageIds.ToList(),
                Source       = request.Source
            }, assertion);

            return(true);
        }
コード例 #17
0
        public async Task <SearchPharmaceuticalPrescriptionResult> Handle(GetOpenedPharmaceuticalPrescriptionsQuery query, CancellationToken token)
        {
            SAMLAssertion assertion;
            var           medicalfile = await _medicalFileQueryRepository.Get(query.MedicalfileId, token);

            if (medicalfile == null)
            {
                throw new UnknownPrescriptionException(query.MedicalfileId, string.Format(Global.UnknownMedicalFile, query.MedicalfileId));
            }

            try
            {
                assertion = SAMLAssertion.Deserialize(query.AssertionToken);
            }
            catch
            {
                throw new BadAssertionTokenException(Global.BadAssertionToken);
            }

            var result = await _prescriptionService.GetOpenedPrescriptions(new GetPrescriptionsParameter
            {
                PatientNiss = medicalfile.PatientNiss,
                Page        = new Page
                {
                    PageNumber = 0
                },
                Assertion = assertion
            }, token);

            return(new SearchPharmaceuticalPrescriptionResult
            {
                HasMoreResults = result.HasMoreResults,
                Prescriptions = result.Prescriptions.Select(_ => new SearchPharmaceuticalPrescriptionResult.PharmaceuticalPrescriptionResult
                {
                    RID = _,
                    Status = "opened"
                }).ToList()
            });
        }
コード例 #18
0
        public async Task <IEnumerable <MessageResult> > Handle(GetMessagesQuery request, CancellationToken cancellationToken)
        {
            SAMLAssertion assertion;

            try
            {
                assertion = SAMLAssertion.Deserialize(request.AssertionToken);
            }
            catch
            {
                throw new BadAssertionTokenException(Global.BadAssertionToken);
            }

            var messagesResult = await _ehealthBoxService.GetMessagesList(new EHealthBoxGetMessagesListRequest
            {
                StartIndex = request.StartIndex,
                EndIndex   = request.EndIndex,
                Source     = request.Source
            }, assertion);

            return(messagesResult.Body.GetMessagesListResponse.MessageLst.Select(_ => _.ToResult()));
        }
コード例 #19
0
        public async Task <GetPharmaceuticalPrescriptionResult> Handle(GetPharmaceuticalPrescriptionQuery query, CancellationToken token)
        {
            SAMLAssertion assertion = null;

            try
            {
                assertion = SAMLAssertion.Deserialize(query.AssertionToken);
            }
            catch
            {
                throw new BadAssertionTokenException(Global.BadAssertionToken);
            }

            var prescription = await _prescriptionService.GetPrescription(new GetPrescriptionParameter
            {
                PrescriptionId = query.PrescriptionId,
                Assertion      = assertion
            }, token);

            if (prescription == null)
            {
                throw new UnknownPrescriptionException(query.PrescriptionId, string.Format(Global.UnknownPrescription, query.PrescriptionId));
            }

            var patient = await _patientQueryRepository.GetByNiss(prescription.PatientNiss, token);

            var cnkCodes = prescription.Medications.Select(m => m.PackageCode);
            var lst      = new List <Task <AmpResult> >();

            foreach (var cnkCode in cnkCodes)
            {
                lst.Add(_ampService.SearchByCnkCode(DeliveryEnvironments.Public.Code, cnkCode, token));
            }

            var ampLst = await Task.WhenAll(lst);

            return(prescription.ToResult(patient, ampLst.ToList()));
        }
コード例 #20
0
        // Create a SAML response with the user's local identity.
        private SAMLResponse CreateSAMLResponse()
        {
            Trace.Write("IdP", "Creating SAML response");

            SAMLResponse samlResponse = new SAMLResponse();

            samlResponse.Destination = Configuration.AssertionConsumerServiceURL;
            Issuer issuer = new Issuer(CreateAbsoluteURL("~/"));

            samlResponse.Issuer = issuer;
            samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);

            SAMLAssertion samlAssertion = new SAMLAssertion();

            samlAssertion.Issuer = issuer;

            Subject                 subject                 = new Subject(new NameID(User.Identity.Name));
            SubjectConfirmation     subjectConfirmation     = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
            SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();

            subjectConfirmationData.Recipient           = Configuration.AssertionConsumerServiceURL;
            subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
            subject.SubjectConfirmations.Add(subjectConfirmation);
            samlAssertion.Subject = subject;

            AuthnStatement authnStatement = new AuthnStatement();

            authnStatement.AuthnContext = new AuthnContext();
            authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Password);
            samlAssertion.Statements.Add(authnStatement);

            samlResponse.Assertions.Add(samlAssertion);

            Trace.Write("IdP", "Created SAML response");

            return(samlResponse);
        }
コード例 #21
0
        private void BuildSamlRequest()
        {
            ClientScript.RegisterStartupScript(typeof(Page), "OpaqueDivider",
                                               @"
                <script language=""javascript"">
                <!--
                    var dividerID = '" + this.SamlAgentDiv.ClientID + @"';
                    var divider = document.getElementById(dividerID);

                    divider.style.visibility = 'visible';
                //-->
	            </script>"    );

            //Creating SAML response
            X509Certificate2 vendorCertificate  = GetVendorCertificate();
            X509Certificate2 selerixCertificate = GetSelerixCertificate();

            //string assertionConsumerServiceURL = "SamlResponse.aspx";
            string assertionConsumerServiceURL = "http://localhost:49000/login.aspx?Path=SAML_TEST";

            string audienceName = "whatever audience";

            SAMLResponse samlResponse = new SAMLResponse();

            samlResponse.Destination = assertionConsumerServiceURL;

            Issuer issuer = new Issuer("Vendor");

            samlResponse.Issuer = issuer;
            samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);

            SAMLAssertion samlAssertion = new SAMLAssertion();

            samlAssertion.Issuer = issuer;

            Subject subject = null;

            //subject = new Subject(new EncryptedID(new NameID(this._EmailText.Text), selerixCertificate, new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl)));
            subject = new Subject(new NameID(this._EmailText.Text));

            SubjectConfirmation     subjectConfirmation     = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
            SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();

            subjectConfirmationData.Recipient           = assertionConsumerServiceURL;
            subjectConfirmationData.NotOnOrAfter        = DateTime.UtcNow.AddHours(1);
            subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;

            subject.SubjectConfirmations.Add(subjectConfirmation);
            samlAssertion.Subject = subject;

            Conditions          conditions          = new Conditions(new TimeSpan(1, 0, 0));
            AudienceRestriction audienceRestriction = new AudienceRestriction();

            audienceRestriction.Audiences.Add(new Audience(audienceName));
            conditions.ConditionsList.Add(audienceRestriction);
            samlAssertion.Conditions = conditions;

            AuthnStatement authnStatement = new AuthnStatement();

            authnStatement.AuthnContext = new AuthnContext();
            authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Unspecified);

            samlAssertion.Statements.Add(authnStatement);

            AttributeStatement attributeStatement = new AttributeStatement();

            Transmittal transmittal = BuildTransmittal();

            if (transmittal != null && !string.IsNullOrEmpty(this._FirstName.Text) && !string.IsNullOrEmpty(this._LastName.Text))
            {
                attributeStatement.Attributes.Add(new SAMLAttribute("Transmittal", SAMLIdentifiers.AttributeNameFormats.Basic, null, SerializationHelper.SerializeToString(transmittal)));
            }

            samlAssertion.Statements.Add(attributeStatement);

//          EncryptedAssertion encryptedAssertion = new EncryptedAssertion(samlAssertion, selerixCertificate, new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl));
//          samlResponse.Assertions.Add(encryptedAssertion);
            samlResponse.Assertions.Add(samlAssertion);

            //Created SAML response

            //Sending SAML response

            // Serialize the SAML response for transmission.
            XmlElement samlResponseXml = samlResponse.ToXml();

            // Sign the SAML response.
            SAMLMessageSignature.Generate(samlResponseXml, vendorCertificate.PrivateKey, vendorCertificate);

            HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
            HttpContext.Current.Response.AddHeader("Pragma", "no-cache");

            IdentityProvider.SendSAMLResponseByHTTPPost(HttpContext.Current.Response, assertionConsumerServiceURL, samlResponseXml, "");// for test purposes
        }
コード例 #22
0
        public Task <SOAPEnvelope <EHealthBoxSendMessageResponseBody> > SendMessage(EHealthBoxSendMessageRequest request, Action <EHealthBoxSendMessageRequestBuilder> callback, SAMLAssertion assertion)
        {
            var builder = EHealthBoxSendMessageRequestBuilder.New();

            callback(builder);
            builder.Build();
            return(SendMessage(builder.Build(), assertion));
        }
コード例 #23
0
        // Process a successful SAML response.
        private void ProcessSuccessSAMLResponse(SAMLResponse samlResponse, string relayState)
        {
            Trace.Write("SP", "Processing successful SAML response");

            // Extract the asserted identity from the SAML response.
            // The SAML assertion may be signed or encrypted and signed.
            SAMLAssertion samlAssertion = null;

            if (samlResponse.GetUnsignedAssertions().Count > 0)
            {
                samlAssertion = samlResponse.GetUnsignedAssertions()[0];
            }
            else if (samlResponse.GetSignedAssertions().Count > 0)
            {
                Trace.Write("SP", "Verifying assertion signature");

                XmlElement samlAssertionXml = samlResponse.GetSignedAssertions()[0];

                // Verify the assertion signature. The embedded signing certificate is used.
                if (!SAMLAssertionSignature.Verify(samlAssertionXml))
                {
                    throw new ArgumentException("The SAML assertion signature failed to verify.");
                }

                samlAssertion = new SAMLAssertion(samlAssertionXml);
            }
            else if (samlResponse.GetEncryptedAssertions().Count > 0)
            {
                Trace.Write("SP", "Decrypting assertion");

                // Load the decryption key.
                X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SPX509Certificate];

                // Decrypt the encrypted assertion.
                XmlElement samlAssertionXml = samlResponse.GetEncryptedAssertions()[0].DecryptToXml(x509Certificate.PrivateKey, null, null);

                if (SAMLAssertionSignature.IsSigned(samlAssertionXml))
                {
                    Trace.Write("SP", "Verifying assertion signature");

                    // Verify the assertion signature. The embedded signing certificate is used.
                    if (!SAMLAssertionSignature.Verify(samlAssertionXml))
                    {
                        throw new ArgumentException("The SAML assertion signature failed to verify.");
                    }
                }

                samlAssertion = new SAMLAssertion(samlAssertionXml);
            }
            else
            {
                throw new ArgumentException("No assertions in response");
            }

            // Get the subject name identifier.
            string userName = null;

            if (samlAssertion.Subject.NameID != null)
            {
                userName = samlAssertion.Subject.NameID.NameIdentifier;
            }

            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentException("The SAML assertion doesn't contain a subject name.");
            }

            // Create a login context for the asserted identity.
            Trace.Write("SP", "Automatically logging in user " + userName);
            FormsAuthentication.SetAuthCookie(userName, false);

            // Get the originally requested resource URL from the relay state, if any.
            string redirectURL = "~/";

            RelayState cachedRelayState = RelayStateCache.Remove(relayState);

            if (cachedRelayState != null)
            {
                redirectURL = cachedRelayState.ResourceURL;
            }

            // Redirect to the originally requested resource URL, if any, or the default page.
            Trace.Write("SP", "Redirecting to " + redirectURL);
            Response.Redirect(redirectURL, false);

            Trace.Write("SP", "Processed successful SAML response");
        }
コード例 #24
0
 public static async Task AddPrescription(SAMLAssertion assertion)
 {
     var recipeService = (IRecipeService)_serviceProvider.GetService(typeof(IRecipeService));
     await recipeService.CreatePrescription("P0", "76020727360", DateTime.Parse("2020-06-25"), null, assertion);
 }
コード例 #25
0
ファイル: SSOService.aspx.cs プロジェクト: HRINY/HRI-Umbraco
        // Create a SAML response with the user's local identity, if any, or indicating an error.
        private SAMLResponse CreateSAMLResponse(AuthnRequest authnRequest)
        {
            Trace.Write("IdP", "Creating SAML response");

            SAMLResponse samlResponse = new SAMLResponse();
            samlResponse.Destination = Configuration.AssertionConsumerServiceURL;
            Issuer issuer = new Issuer(CreateAbsoluteURL("~/"));
            samlResponse.Issuer = issuer;

            if (User.Identity.IsAuthenticated) {
                samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);

                SAMLAssertion samlAssertion = new SAMLAssertion();
                samlAssertion.Issuer = issuer;

                Subject subject = new Subject(new NameID(User.Identity.Name));
                SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
                SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();
                subjectConfirmationData.InResponseTo = authnRequest.ID;
                subjectConfirmationData.Recipient = Configuration.AssertionConsumerServiceURL;
                subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
                subject.SubjectConfirmations.Add(subjectConfirmation);
                samlAssertion.Subject = subject;

                AuthnStatement authnStatement = new AuthnStatement();
                authnStatement.AuthnContext = new AuthnContext();
                authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Password);
                samlAssertion.Statements.Add(authnStatement);

                samlResponse.Assertions.Add(samlAssertion);
            } else {
                samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Responder, SAMLIdentifiers.SecondaryStatusCodes.AuthnFailed, "The user is not authenticated at the identity provider");
            }

            Trace.Write("IdP", "Created SAML response");

            return samlResponse;
        }
コード例 #26
0
        private string BuildSAML()
        {
            var strIssuer   = queryParameters.FirstOrDefault(i => i.Key == "issuer").Value;
            var member      = queryParameters.FirstOrDefault(i => i.Key == "member").Value;
            var userEmail   = queryParameters.FirstOrDefault(i => i.Key == "userEmail").Value;
            var cn          = queryParameters.FirstOrDefault(i => i.Key == "cn").Value;
            var uid         = queryParameters.FirstOrDefault(i => i.Key == "uid").Value;
            var pfxLocation = queryParameters.FirstOrDefault(i => i.Key == "pfxLocation").Value;
            var pfxPwd      = queryParameters.FirstOrDefault(i => i.Key == "pfxPwd").Value;

            var samlResponse = new SAMLResponse();

            samlResponse.Issuer      = new Issuer(strIssuer);
            samlResponse.Destination = strIssuer;

            var samlAssertion = new SAMLAssertion();

            samlAssertion.Issuer     = new Issuer(strIssuer);
            samlAssertion.Subject    = new Subject(new NameID(userEmail, null, null, SAMLIdentifiers.NameIdentifierFormats.EmailAddress, null));
            samlAssertion.Conditions = new Conditions(new TimeSpan(1, 0, 0));

            var authnStatement = new AuthnStatement();

            authnStatement.AuthnContext = new AuthnContext();
            authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.PasswordProtectedTransport);
            samlAssertion.Statements.Add(authnStatement);

            var attributeStatement = new AttributeStatement();

            attributeStatement.Attributes.Add(new SAMLAttribute("member", SAMLIdentifiers.AttributeNameFormats.Basic, null, member));
            samlAssertion.Statements.Add(attributeStatement);

            attributeStatement = new AttributeStatement();
            attributeStatement.Attributes.Add(new SAMLAttribute("mail", SAMLIdentifiers.AttributeNameFormats.Basic, null, userEmail));
            samlAssertion.Statements.Add(attributeStatement);

            attributeStatement = new AttributeStatement();
            attributeStatement.Attributes.Add(new SAMLAttribute("cn", SAMLIdentifiers.AttributeNameFormats.Basic, null, cn));
            samlAssertion.Statements.Add(attributeStatement);

            attributeStatement = new AttributeStatement();
            attributeStatement.Attributes.Add(new SAMLAttribute("uid", SAMLIdentifiers.AttributeNameFormats.Basic, null, uid));
            samlAssertion.Statements.Add(attributeStatement);

            samlResponse.Assertions.Add(samlAssertion);

            if (true)
            {
                var x509Certificate = Util.LoadSignKeyAndCertificate(pfxLocation, pfxPwd);
                var signedXml       = new SignedXml(samlResponse.ToXml());
                signedXml.SigningKey = x509Certificate.PrivateKey;

                var keyInfo = new KeyInfo();
                keyInfo.AddClause(new KeyInfoX509Data(x509Certificate));
                signedXml.KeyInfo = keyInfo;

                // Create a reference to be signed.
                var reference = new Reference();
                reference.Uri = "#" + samlAssertion.ID;

                var env = new XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(env);
                signedXml.AddReference(reference);
                signedXml.ComputeSignature();

                samlResponse.Signature = signedXml.GetXml();
            }

            var result = samlResponse.ToXml().OuterXml.ToString();

            File.WriteAllText("SAMLPayload.xml", result);
            return(Util.EncodeToBase64(result));
        }
コード例 #27
0
        public async Task <CreatePrescriptionResult> CreatePrescription(string prescriptionType, string patientId, DateTime expirationDateTime, kmehrmessageType msgType, SAMLAssertion assertion)
        {
            var orgCertificate = _keyStoreManager.GetOrgAuthCertificate();
            var recipeETK      = await _etkService.GetRecipeETK();

            var kgssResponse = await _kgssService.GetKGSS(new System.Collections.Generic.List <CredentialType>
            {
                new CredentialType
                {
                    Namespace = Constants.AttributeStatementNamespaces.Identification,
                    Name      = Constants.AttributeStatementNames.PersonSSIN,
                    Value     = assertion.AttributeStatement.Attribute.First(_ => _.AttributeNamespace == EHealth.Constants.AttributeStatementNamespaces.Identification).AttributeValue
                },
                new CredentialType
                {
                    Namespace = Constants.AttributeStatementNamespaces.Certified,
                    Name      = assertion.AttributeStatement.Attribute.First(_ => _.AttributeNamespace == EHealth.Constants.AttributeStatementNamespaces.Certified).AttributeName
                }
            });

            var prescriptionPayload = msgType.SerializeToByte(false, true);
            var compressedPayload   = Compress(prescriptionPayload);

            byte[] encryptedPayload;
            using (var aes = Aes.Create())
            {
                aes.Padding      = PaddingMode.PKCS7;
                aes.Mode         = CipherMode.CBC;
                aes.KeySize      = 128;
                aes.Key          = Convert.FromBase64String(kgssResponse.NewKey);
                encryptedPayload = TripleWrapper.Seal(compressedPayload, orgCertificate, kgssResponse.NewKeyIdentifier, aes);
            }

            var symKey = new TripleDESCryptoServiceProvider
            {
                Padding = PaddingMode.None,
                Mode    = CipherMode.ECB
            };
            var prescriptionParameter = new CreatePrescriptionParameter
            {
                Prescription      = Convert.ToBase64String(encryptedPayload),
                PrescriptionType  = prescriptionType,
                FeedbackRequested = false,
                KeyId             = kgssResponse.NewKeyIdentifier,
                SymmKey           = Convert.ToBase64String(symKey.Key),
                PatientId         = patientId,
                ExpirationDate    = expirationDateTime.ToString("yyyy-MM-dd"),
                Vision            = ""
            };
            var serializedPrescriptionParameter = Encoding.UTF8.GetBytes(prescriptionParameter.Serialize().SerializeToString(false, true));

            byte[] sealedContent             = TripleWrapper.Seal(serializedPrescriptionParameter, orgCertificate, recipeETK.Certificate);
            var    issueInstant              = DateTime.UtcNow;
            var    createPrescriptionRequest = new CreatePrescriptionRequest
            {
                IssueInstant = issueInstant,
                Id           = $"id{Guid.NewGuid().ToString()}",
                ProgramId    = "Medikit",
                AdministrativeInformation = new CreatePrescriptionAdministrativeInformationType
                {
                    KeyIdentifier          = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(kgssResponse.NewKeyIdentifier)),
                    PrescriptionVersion    = "kmehr_1.29",
                    ReferenceSourceVersion = "samv2:ABCDE999999999999",
                    PrescriptionType       = prescriptionType
                },
                SecuredCreatePrescriptionRequest = new SecuredContentType
                {
                    SecuredContent = Convert.ToBase64String(sealedContent)
                }
            };
            var soapRequest = SOAPRequestBuilder <CreatePrescriptionRequestBody> .New(new CreatePrescriptionRequestBody
            {
                Id      = $"id-{Guid.NewGuid().ToString()}",
                Request = createPrescriptionRequest
            })
                              .AddTimestamp(issueInstant, issueInstant.AddHours(1))
                              .AddSAMLAssertion(assertion)
                              .AddReferenceToSAMLAssertion()
                              .SignWithCertificate(orgCertificate)
                              .Build();

            var result = await _soapClient.Send(soapRequest, new Uri(_options.PrescriberUrl), "urn:be:fgov:ehealth:recipe:protocol:v4:createPrescription");

            var xml = await result.Content.ReadAsStringAsync();

            result.EnsureSuccessStatusCode();
            var response = SOAPEnvelope <CreatePrescriptionResponseBody> .Deserialize(xml);

            var securedContent = response.Body.CreatePrescriptionResponse.SecuredGetPrescriptionResponse.SecuredContent;

            byte[] decrypted;
            using (var decryptor = symKey.CreateDecryptor())
            {
                var payload = Convert.FromBase64String(securedContent);
                decrypted = decryptor.TransformFinalBlock(payload, 0, payload.Length);
            }

            xml = Encoding.UTF8.GetString(decrypted);
            xml = xml.ClearBadFormat();
            return(CreatePrescriptionResult.Deserialize(xml));
        }
コード例 #28
0
        public async Task <SOAPEnvelope <EHealthBoxGetMessagesListResponseBody> > GetMessagesList(EHealthBoxGetMessagesListRequest request, SAMLAssertion assertion)
        {
            var issueInstant   = DateTime.UtcNow;
            var orgCertificate = _keyStoreManager.GetOrgAuthCertificate();
            var soapRequest    = SOAPRequestBuilder <EHealthBoxGetMessagesListRequestBody> .New(new EHealthBoxGetMessagesListRequestBody
            {
                Id      = $"id-{Guid.NewGuid().ToString()}",
                Request = request
            })
                                 .AddTimestamp(issueInstant, issueInstant.AddHours(1))
                                 .AddSAMLAssertion(assertion)
                                 .AddReferenceToSAMLAssertion()
                                 .SignWithCertificate(orgCertificate)
                                 .Build();

            var httpResult = await _soapClient.Send(soapRequest, new Uri(_options.EHealthboxConsultation), "urn:be:fgov:ehealth:ehbox:consultation:protocol:v3:getMessagesList");

            var xml = await httpResult.Content.ReadAsStringAsync();

            httpResult.EnsureSuccessStatusCode();
            var result = SOAPEnvelope <EHealthBoxGetMessagesListResponseBody> .Deserialize(xml);

            return(result);
        }
コード例 #29
0
ファイル: AuthController.cs プロジェクト: Inforward/Guideport
        private static XmlElement CreateSamlResponse(string assertionConsumerServiceUrl, List <SAMLAttribute> attributes, string requestId = null, bool signAssertion = false, bool signResponse = false, bool encryptAssertion = false)
        {
            var samlResponse = new SAMLResponse {
                Destination = assertionConsumerServiceUrl
            };
            var issuer = new Issuer(SAMLConfiguration.Current.IdentityProviderConfiguration.Name);
            var issuerX509CertificateFilePath = Path.Combine(HttpRuntime.AppDomainAppPath, SAMLConfiguration.Current.IdentityProviderConfiguration.CertificateFile);
            var issuerX509Certificate         = new X509Certificate2(issuerX509CertificateFilePath, SAMLConfiguration.Current.IdentityProviderConfiguration.CertificatePassword);
            var partner       = SessionHelper.Get <string>(PartnerSpSessionKey) ?? SAMLConfiguration.Current.ServiceProviderConfiguration.Name;
            var partnerConfig = SAMLConfiguration.Current.PartnerServiceProviderConfigurations[partner];
            var partnerX509CertificateFilePath = string.Empty;
            var partnerX509Certificate         = null as X509Certificate2;

            if (partnerConfig != null)
            {
                partnerX509CertificateFilePath = Path.Combine(HttpRuntime.AppDomainAppPath, partnerConfig.CertificateFile);
                partnerX509Certificate         = new X509Certificate2(partnerX509CertificateFilePath);
                signAssertion    = partnerConfig.SignAssertion;
                signResponse     = partnerConfig.SignSAMLResponse;
                encryptAssertion = partnerConfig.EncryptAssertion;
            }

            samlResponse.Issuer       = issuer;
            samlResponse.Status       = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);
            samlResponse.IssueInstant = DateTime.Now;
            samlResponse.InResponseTo = requestId;

            var samlAssertion = new SAMLAssertion {
                Issuer = issuer, IssueInstant = samlResponse.IssueInstant
            };

            var profileId               = attributes.Where(a => a.Name == PortalClaimTypes.ProfileId).Select(a => a.Values[0].ToString()).FirstOrDefault();
            var subject                 = new Subject(new NameID(profileId));
            var subjectConfirmation     = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
            var subjectConfirmationData = new SubjectConfirmationData {
                Recipient = assertionConsumerServiceUrl
            };

            subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
            subject.SubjectConfirmations.Add(subjectConfirmation);
            samlAssertion.Subject = subject;

            var conditions          = new Conditions(DateTime.Now, DateTime.Now.AddDays(1));
            var audienceRestriction = new AudienceRestriction();

            audienceRestriction.Audiences.Add(new Audience(partner));
            conditions.ConditionsList.Add(audienceRestriction);
            samlAssertion.Conditions = conditions;

            var authnStatement = new AuthnStatement {
                AuthnContext = new AuthnContext(), AuthnInstant = samlResponse.IssueInstant
            };

            authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.X509);
            samlAssertion.Statements.Add(authnStatement);

            attributes.ForEach(a =>
            {
                var attributeStatement = new AttributeStatement();

                attributeStatement.Attributes.Add(a);
                samlAssertion.Statements.Add(attributeStatement);
            });

            var samlAssertionXml = samlAssertion.ToXml();

            if (signAssertion)
            {
                SAMLAssertionSignature.Generate(samlAssertionXml, issuerX509Certificate.PrivateKey, issuerX509Certificate);
            }

            if (encryptAssertion)
            {
                var encryptedAssertion = new EncryptedAssertion(samlAssertionXml, partnerX509Certificate);

                samlResponse.Assertions.Add(encryptedAssertion.ToXml());
            }
            else
            {
                samlResponse.Assertions.Add(samlAssertionXml);
            }

            var samlResponseXml = samlResponse.ToXml();

            if (signResponse)
            {
                SAMLMessageSignature.Generate(samlResponseXml, issuerX509Certificate.PrivateKey, issuerX509Certificate);
            }

            return(samlResponseXml);
        }
コード例 #30
0
        private static string BuildSAMLRequest(IList <string> attributes)
        {
            var strIssuer    = "https://sso.staging.gnohie.org/MirthSignOn-idp/ssoresp";
            var samlResponse = new SAMLResponse();

            samlResponse.Issuer      = new Issuer(strIssuer);
            samlResponse.Destination = strIssuer;

            var samlAssertion = new SAMLAssertion();

            samlAssertion.Issuer     = new Issuer(strIssuer);
            samlAssertion.Subject    = new Subject(new NameID(attributes.ElementAt(1), null, null, SAMLIdentifiers.NameIdentifierFormats.EmailAddress, null));
            samlAssertion.Conditions = new Conditions(new TimeSpan(1, 0, 0));

            var authnStatement = new AuthnStatement();

            authnStatement.AuthnContext = new AuthnContext();
            authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.PasswordProtectedTransport);
            samlAssertion.Statements.Add(authnStatement);

            var attributeStatement = new AttributeStatement();

            attributeStatement.Attributes.Add(new SAMLAttribute("member", SAMLIdentifiers.AttributeNameFormats.Basic, null, attributes.ElementAt(0)));
            samlAssertion.Statements.Add(attributeStatement);

            attributeStatement = new AttributeStatement();
            attributeStatement.Attributes.Add(new SAMLAttribute("mail", SAMLIdentifiers.AttributeNameFormats.Basic, null, attributes.ElementAt(1)));
            samlAssertion.Statements.Add(attributeStatement);

            attributeStatement = new AttributeStatement();
            attributeStatement.Attributes.Add(new SAMLAttribute("cn", SAMLIdentifiers.AttributeNameFormats.Basic, null, attributes.ElementAt(2)));
            samlAssertion.Statements.Add(attributeStatement);

            attributeStatement = new AttributeStatement();
            attributeStatement.Attributes.Add(new SAMLAttribute("uid", SAMLIdentifiers.AttributeNameFormats.Basic, null, attributes.ElementAt(3)));
            samlAssertion.Statements.Add(attributeStatement);

            samlResponse.Assertions.Add(samlAssertion);

            if (true)
            {
                var x509Certificate = Util.LoadSignKeyAndCertificate();
                var signedXml       = new SignedXml(samlResponse.ToXml());
                signedXml.SigningKey = x509Certificate.PrivateKey;

                var keyInfo = new KeyInfo();
                keyInfo.AddClause(new KeyInfoX509Data(x509Certificate));
                signedXml.KeyInfo = keyInfo;

                // Create a reference to be signed.
                var reference = new Reference();
                reference.Uri = "#" + samlAssertion.ID;

                var env = new XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(env);
                signedXml.AddReference(reference);
                signedXml.ComputeSignature();

                samlResponse.Signature = signedXml.GetXml();
            }

            //samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);

            var result = samlResponse.ToXml().OuterXml.ToString();

            File.WriteAllText("SAMLPayload.xml", result);
            return(Util.EncodeToBase64(result));
        }
コード例 #31
0
        public async Task <string> Handle(AddPharmaceuticalPrescriptionCommand command, CancellationToken token)
        {
            SAMLAssertion assertion;
            var           medicalfile = await _medicalfileQueryRepository.Get(command.MedicalfileId, token);

            if (medicalfile == null)
            {
                throw new UnknownPatientException(command.MedicalfileId, string.Format(Global.UnknownMedicalFile, command.MedicalfileId));
            }

            try
            {
                assertion = SAMLAssertion.Deserialize(command.AssertionToken);
            }
            catch
            {
                throw new BadAssertionTokenException(Global.BadAssertionToken);
            }

            var createDateTime = DateTime.UtcNow;

            if (command.CreateDateTime != null)
            {
                createDateTime = command.CreateDateTime.Value;
            }

            var niss       = assertion.AttributeStatement.Attribute.First(_ => _.AttributeNamespace == EHealth.Constants.AttributeStatementNamespaces.Identification).AttributeValue;
            var profession = assertion.AttributeStatement.Attribute.First(_ => _.AttributeNamespace == EHealth.Constants.AttributeStatementNamespaces.Certified).AttributeName;
            var cbe        = _keyStoreManager.GetOrgAuthCertificate().Certificate.ExtractCBE();
            var msgType    = new KmehrMessageBuilder()
                             .AddSender((_) =>
            {
                _.AddHealthCareParty((_) =>
                {
                    _.AddOrganization(cbe, "application", _options.ProductName);
                });
                _.AddHealthCareParty((_) =>
                {
                    _.AddPerson(niss, MAPPING_CLAIM_TO_HCPARTY[profession], string.Empty, string.Empty);
                });
            })
                             .AddRecipient((_) =>
            {
                _.AddHealthCareParty((s) =>
                {
                    s.AddOrganization("RECIPE", "orgpublichealth", "Recip-e");
                });
            })
                             .AddFolder("1", (_) =>
            {
                _.New(medicalfile.PatientNiss, medicalfile.PatientLastname, new string[] { medicalfile.PatientFirstname });
            }, (_) =>
            {
                _.AddTransaction((tr) =>
                {
                    tr.NewPharmaceuticalPrescriptionTransaction("1", createDateTime, true, true, command.ExpirationDateTime)
                    .AddAuthor(niss, MAPPING_CLAIM_TO_HCPARTY[profession], string.Empty, string.Empty)
                    .AddTransactionHeading((h) =>
                    {
                        h.NewPrescriptionHeading("1");
                        foreach (var pharmaPrescription in command.Medications)
                        {
                            h.AddMedicationTransactionItem((ti) =>
                            {
                                ti.SetMedicinalProduct(pharmaPrescription.PackageCode, string.Empty);
                                if (pharmaPrescription.Posology.Type.Code == PosologyTypes.FreeText.Code)
                                {
                                    var freeText = pharmaPrescription.Posology as AddPosologyFreeTextCommand;
                                    ti.SetPosologyFreeText(freeText.Content, DEFAULT_LANGUAGE);
                                }
                                else
                                {
                                    // TODO : MANAGE STRUCTURED POSOLOGY.
                                }

                                if (pharmaPrescription.BeginMoment != null)
                                {
                                    ti.SetBeginMoment(pharmaPrescription.BeginMoment.Value);
                                }

                                if (!string.IsNullOrWhiteSpace(pharmaPrescription.InstructionForPatient))
                                {
                                    ti.SetInstructionForPatient(pharmaPrescription.InstructionForPatient, DEFAULT_LANGUAGE);
                                }

                                if (!string.IsNullOrWhiteSpace(pharmaPrescription.InstructionForReimbursement))
                                {
                                    ti.SetInstructionForReimbursement(pharmaPrescription.InstructionForReimbursement, DEFAULT_LANGUAGE);
                                }
                            });
                        }
                    });
                });
            })
                             .Build(createDateTime);
            var result = await _recipeService.CreatePrescription(Enum.GetName(typeof(PrescriptionTypes), command.PrescriptionType), medicalfile.PatientNiss, command.ExpirationDateTime.Value, msgType, assertion);

            return(result.RID);
        }
コード例 #32
0
        // Process a successful SAML response.
        private void ProcessSuccessSAMLResponse(SAMLResponse samlResponse, string relayState)
        {
            //Processing successful SAML response

            // Load the decryption key.
            X509Certificate2 x509Certificate = GetSelerixCertificate();

            // Extract the asserted identity from the SAML response.
            SAMLAssertion samlAssertion = null;

            if (samlResponse.GetAssertions().Count > 0)
            {
                samlAssertion = samlResponse.GetAssertions()[0];
            }
            else if (samlResponse.GetEncryptedAssertions().Count > 0)
            {
                //"Decrypting assertion");
                samlAssertion = samlResponse.GetEncryptedAssertions()[0].Decrypt(x509Certificate.PrivateKey, null);
            }
            else if (samlResponse.GetSignedAssertions().Count > 0)
            {
                samlAssertion = new SAMLAssertion(samlResponse.GetSignedAssertions()[0]);
            }
            else
            {
                throw new ArgumentException("No assertions in response");
            }

            // Get the subject name identifier.
            string userName = null;

            if (samlAssertion.Subject.NameID != null)
            {
                userName = samlAssertion.Subject.NameID.NameIdentifier;
            }
            else if (samlAssertion.Subject.EncryptedID != null)
            {
                //"Decrypting ID");
                NameID nameID = samlAssertion.Subject.EncryptedID.Decrypt(x509Certificate.PrivateKey, null);
                userName = nameID.NameIdentifier;
            }
            else
            {
                throw new ArgumentException("No name in subject");
            }

            Dictionary <string, string> outputData = new Dictionary <string, string>();

            foreach (AttributeStatement attributeStatement in samlAssertion.GetAttributeStatements())
            {
                foreach (SAMLAttribute samlAttribute in attributeStatement.GetUnencryptedAttributes())
                {
                    foreach (AttributeValue attributeValue in samlAttribute.Values)
                    {
                        if (!outputData.ContainsKey(samlAttribute.Name))
                        {
                            outputData.Add(samlAttribute.Name, attributeValue.ToString());
                        }
                        else
                        {
                            outputData[samlAttribute.Name] = attributeValue.ToString();
                        }
                    }
                }
                foreach (EncryptedAttribute encryptedAttribute in attributeStatement.GetEncryptedAttributes())
                {
                    SAMLAttribute samlAttribute = encryptedAttribute.Decrypt(x509Certificate.PrivateKey, null);
                    foreach (AttributeValue attributeValue in samlAttribute.Values)
                    {
                        if (!outputData.ContainsKey(samlAttribute.Name))
                        {
                            outputData.Add(samlAttribute.Name, attributeValue.ToString());
                        }
                        else
                        {
                            outputData[samlAttribute.Name] = attributeValue.ToString();
                        }
                    }
                }
            }

            // prevent the output of aspx page from being cached by the browser
            Response.AddHeader("Cache-Control", "no-cache");
            Response.AddHeader("Pragma", "no-cache");

            if (outputData.ContainsKey("Transmittal"))
            {
                Session["Transmittal"] = Selerix.Foundation.Data.SerializationHelper.DeserializeFromString(outputData["Transmittal"], typeof(Transmittal));
            }
            else
            {
                Session["Transmittal"] = null;
            }

            Session["SAMLParameters"] = outputData;

            Response.Redirect("~/ShowTransmittal.aspx", false);

            //"Processed successful SAML response");
        }
コード例 #33
0
        // Process a successful SAML response.
        private void ProcessSuccessSAMLResponse(SAMLResponse samlResponse, string relayState)
        {
            Trace.Write("SP", "Processing successful SAML response");

            // Extract the asserted identity from the SAML response.
            // The SAML assertion may be signed or encrypted and signed.
            SAMLAssertion samlAssertion = null;

            if (samlResponse.GetAssertions().Count > 0) {
                samlAssertion = samlResponse.GetAssertions()[0];
            } else if (samlResponse.GetSignedAssertions().Count > 0) {
                Trace.Write("SP", "Verifying assertion signature");

                XmlElement samlAssertionXml = samlResponse.GetSignedAssertions()[0];

                // Verify the assertion signature. The embedded signing certificate is used.
                if (!SAMLAssertionSignature.Verify(samlAssertionXml)) {
                    throw new ArgumentException("The SAML assertion signature failed to verify.");
                }

                samlAssertion = new SAMLAssertion(samlAssertionXml);
            } else if (samlResponse.GetEncryptedAssertions().Count > 0) {
                Trace.Write("SP", "Decrypting assertion");

                // Load the decryption key.
                X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SPX509Certificate];

                // Decrypt the encrypted assertion.
                XmlElement samlAssertionXml = samlResponse.GetEncryptedAssertions()[0].DecryptToXml(x509Certificate.PrivateKey, null, null);

                if (SAMLAssertionSignature.IsSigned(samlAssertionXml)) {
                    Trace.Write("SP", "Verifying assertion signature");

                    // Verify the assertion signature. The embedded signing certificate is used.
                    if (!SAMLAssertionSignature.Verify(samlAssertionXml)) {
                        throw new ArgumentException("The SAML assertion signature failed to verify.");
                    }
                }

                samlAssertion = new SAMLAssertion(samlAssertionXml);
            } else {
                throw new ArgumentException("No assertions in response");
            }

            // Get the subject name identifier.
            string userName = null;

            if (samlAssertion.Subject.NameID != null) {
                userName = samlAssertion.Subject.NameID.NameIdentifier;
            }

            if (string.IsNullOrEmpty(userName)) {
                throw new ArgumentException("The SAML assertion doesn't contain a subject name.");
            }

            // Create a login context for the asserted identity.
            Trace.Write("SP", "Automatically logging in user " + userName);
            FormsAuthentication.SetAuthCookie(userName, false);

            // Get the originally requested resource URL from the relay state, if any.
            string redirectURL = "~/";

            RelayState cachedRelayState = RelayStateCache.Remove(relayState);

            if (cachedRelayState != null) {
                redirectURL = cachedRelayState.ResourceURL;
            }

            // Redirect to the originally requested resource URL, if any, or the default page.
            Trace.Write("SP", "Redirecting to " + redirectURL);
            Response.Redirect(redirectURL, false);

            Trace.Write("SP", "Processed successful SAML response");
        }
コード例 #34
0
        /// <summary>
        /// Handles the Click event of the submitButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void submitButton_Click(object sender, EventArgs e)
        {
            Transmittal transmittal = null;
            string      employeeID  = this._EmployeeID.Text;

            if (!string.IsNullOrEmpty(this._XMLText.Text))
            {
                try
                {
                    transmittal = (Transmittal)SerializationHelper.DeserializeFromString(this._XMLText.Text, typeof(Transmittal));
                }
                catch (Exception exception)
                {
                    this._XMLText.Text = exception.Message;
                    Exception inner = exception.InnerException;

                    while (inner != null)
                    {
                        this._XMLText.Text += "\n" + inner.Message;
                        inner = inner.InnerException;
                    }

                    this._XMLText.Text = PrepareSourceCode(this._XMLText.Text);
                }
            }

            if (!string.IsNullOrEmpty(employeeID) && transmittal != null && transmittal.Applicants != null && transmittal.Applicants.Count > 0)
            {
                transmittal.Applicants[0].EmployeeIdent = employeeID;
            }

            Session["Transmittal"] = transmittal;

            //Creating SAML responce
            X509Certificate2 vendorCertificate  = GetVendorCertificate();
            X509Certificate2 selerixCertificate = GetSelerixCertificate();

            string assertionConsumerServiceURL = "SamlResponse.aspx";
            string audienceName = "whatever audience";

            SAMLResponse samlResponse = new SAMLResponse();

            samlResponse.Destination = assertionConsumerServiceURL;
            Issuer issuer = new Issuer("Vendor");

            samlResponse.Issuer = issuer;
            samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);

            SAMLAssertion samlAssertion = new SAMLAssertion();

            samlAssertion.Issuer = issuer;

            Subject subject = null;

//          subject = new Subject(new EncryptedID(new NameID(employeeID), selerixCertificate, new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl))); //employee ID
            subject = new Subject(new NameID(employeeID)); //employee ID

            SubjectConfirmation     subjectConfirmation     = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
            SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();

            subjectConfirmationData.Recipient           = assertionConsumerServiceURL;
            subjectConfirmationData.NotOnOrAfter        = DateTime.UtcNow.AddHours(1);
            subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
            subject.SubjectConfirmations.Add(subjectConfirmation);

            samlAssertion.Subject = subject;

            Conditions          conditions          = new Conditions(new TimeSpan(1, 0, 0));
            AudienceRestriction audienceRestriction = new AudienceRestriction();

            audienceRestriction.Audiences.Add(new Audience(audienceName));
            conditions.ConditionsList.Add(audienceRestriction);
            samlAssertion.Conditions = conditions;

            AuthnStatement authnStatement = new AuthnStatement();

            authnStatement.AuthnContext = new AuthnContext();
            authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Unspecified);
            samlAssertion.Statements.Add(authnStatement);

            AttributeStatement attributeStatement = new AttributeStatement();

            if (transmittal != null)
            {
                attributeStatement.Attributes.Add(new SAMLAttribute("Transmittal", SAMLIdentifiers.AttributeNameFormats.Basic, null, SerializationHelper.SerializeToString(transmittal)));

                if (transmittal.Applicants != null && transmittal.Applicants.Count > 0)
                {
                    transmittal.Applicants[0].EmployeeIdent = employeeID;
                }
            }

            //Check for Transmittal Options
            for (int i = 0; i < _TransmittalOptionsList.Items.Count; i++)
            {
                string answer = "no";

                if (_TransmittalOptionsList.Items[i].Selected)
                {
                    answer = "yes";
                }

                if (_TransmittalOptionsList.Items[i].Value == "HeaderAndFooter")
                {
                    attributeStatement.Attributes.Add(new SAMLAttribute("HeaderAndFooter", SAMLIdentifiers.AttributeNameFormats.Basic, null, answer));
                }
                else if (_TransmittalOptionsList.Items[i].Value == "Sidebar")
                {
                    attributeStatement.Attributes.Add(new SAMLAttribute("Sidebar", SAMLIdentifiers.AttributeNameFormats.Basic, null, answer));
                }
                else if (_TransmittalOptionsList.Items[i].Value == "PersonalInfo")
                {
                    attributeStatement.Attributes.Add(new SAMLAttribute("PersonalInfo", SAMLIdentifiers.AttributeNameFormats.Basic, null, answer));
                }
                else if (_TransmittalOptionsList.Items[i].Value == "Welcome")
                {
                    attributeStatement.Attributes.Add(new SAMLAttribute("Welcome", SAMLIdentifiers.AttributeNameFormats.Basic, null, answer));
                }
                else if (_TransmittalOptionsList.Items[i].Value == "Review")
                {
                    attributeStatement.Attributes.Add(new SAMLAttribute("Review", SAMLIdentifiers.AttributeNameFormats.Basic, null, answer));
                }
            }

            samlAssertion.Statements.Add(attributeStatement);

//          EncryptedAssertion encryptedAssertion = new EncryptedAssertion(samlAssertion, selerixCertificate, new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl));
//          samlResponse.Assertions.Add(encryptedAssertion);
            samlResponse.Assertions.Add(samlAssertion);

            //Created SAML response

            //Sending SAML response

            // Serialize the SAML response for transmission.
            XmlElement samlResponseXml = samlResponse.ToXml();

            // Sign the SAML response.
            SAMLMessageSignature.Generate(samlResponseXml, vendorCertificate.PrivateKey, vendorCertificate);

            HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
            HttpContext.Current.Response.AddHeader("Pragma", "no-cache");

            IdentityProvider.SendSAMLResponseByHTTPPost(HttpContext.Current.Response, assertionConsumerServiceURL, samlResponseXml, "");// for test purposes
        }
コード例 #35
0
        public async Task <ListRidsHistoryResult> GetHistoryPrescriptions(string patientId, Page page, SAMLAssertion assertion)
        {
            var orgCertificate = _keyStoreManager.GetOrgAuthCertificate();
            var issueInstant   = DateTime.UtcNow;
            var recipeETK      = await _etkService.GetRecipeETK();

            var symKey = new TripleDESCryptoServiceProvider();

            symKey.Padding = PaddingMode.None;
            symKey.Mode    = CipherMode.ECB;
            var listPrescriptionHistoryParameter = new ListPrescriptionHistoryParameter
            {
                PatientId = patientId,
                Page      = page,
                SymmKey   = Convert.ToBase64String(symKey.Key)
            };
            var serializedPrescriptionParameter = Encoding.UTF8.GetBytes(listPrescriptionHistoryParameter.Serialize().SerializeToString(false, true));

            byte[] sealedContent = TripleWrapper.Seal(serializedPrescriptionParameter, orgCertificate, recipeETK.Certificate);
            var    listPrescriptionHistoryRequest = new ListPrescriptionHistoryRequest
            {
                Id           = $"id{Guid.NewGuid().ToString()}",
                IssueInstant = issueInstant,
                ProgramId    = _options.ProductName,
                SecuredListRidsHistoryRequest = new SecuredContentType
                {
                    SecuredContent = Convert.ToBase64String(sealedContent)
                }
            };

            var soapRequest = SOAPRequestBuilder <ListPrescriptionHistoryRequestBody> .New(new ListPrescriptionHistoryRequestBody
            {
                Id      = $"id-{Guid.NewGuid().ToString()}",
                Request = listPrescriptionHistoryRequest
            })
                              .AddTimestamp(issueInstant, issueInstant.AddHours(1))
                              .AddSAMLAssertion(assertion)
                              .AddReferenceToSAMLAssertion()
                              .SignWithCertificate(orgCertificate)
                              .Build();

            var result = await _soapClient.Send(soapRequest, new Uri(_options.PrescriberUrl), "urn:be:fgov:ehealth:recipe:protocol:v4:listRidsHistory");

            result.EnsureSuccessStatusCode();
            var xml = await result.Content.ReadAsStringAsync();

            var response = SOAPEnvelope <ListPrescriptionHistoryResponseBody> .Deserialize(xml);

            var securedContent = response.Body.ListPrescriptionHistoryResponse.SecuredListRidsHistoryResponse.SecuredContent;

            byte[] decrypted;
            using (var decryptor = symKey.CreateDecryptor())
            {
                var payload = Convert.FromBase64String(securedContent);
                decrypted = decryptor.TransformFinalBlock(payload, 0, payload.Length);
            }

            xml = Encoding.UTF8.GetString(decrypted);
            xml = xml.ClearBadFormat();
            var res = ListRidsHistoryResult.Deserialize(xml);

            return(res);
        }
コード例 #36
0
        public async Task <GetPrescriptionResult> GetPrescription(string rid, SAMLAssertion assertion)
        {
            var orgCertificate = _keyStoreManager.GetOrgAuthCertificate();
            var issueInstant   = DateTime.UtcNow;
            var recipeETK      = await _etkService.GetRecipeETK();

            var symKey = new TripleDESCryptoServiceProvider
            {
                Padding = PaddingMode.None,
                Mode    = CipherMode.ECB
            };
            var getPrescriptionParameter = new GetPrescriptionForPrescriberParameter
            {
                Rid     = rid,
                SymmKey = Convert.ToBase64String(symKey.Key)
            };
            var serializedPrescriptionParameter = Encoding.UTF8.GetBytes(getPrescriptionParameter.Serialize().SerializeToString(false, true));

            byte[] sealedContent          = TripleWrapper.Seal(serializedPrescriptionParameter, orgCertificate, recipeETK.Certificate);
            var    getPrescriptionRequest = new GetPrescriptionRequest
            {
                Id           = $"id{Guid.NewGuid().ToString()}",
                IssueInstant = issueInstant,
                ProgramId    = _options.ProductName,
                SecuredGetPrescriptionRequest = new SecuredContentType
                {
                    SecuredContent = Convert.ToBase64String(sealedContent)
                }
            };

            var soapRequest = SOAPRequestBuilder <GetPrescriptionRequestBody> .New(new GetPrescriptionRequestBody
            {
                Id      = $"id-{Guid.NewGuid().ToString()}",
                Request = getPrescriptionRequest
            })
                              .AddTimestamp(issueInstant, issueInstant.AddHours(1))
                              .AddSAMLAssertion(assertion)
                              .AddReferenceToSAMLAssertion()
                              .SignWithCertificate(orgCertificate)
                              .Build();

            var result = await _soapClient.Send(soapRequest, new Uri(_options.PrescriberUrl), "urn:be:fgov:ehealth:recipe:protocol:v4:getPrescription");

            var xml = await result.Content.ReadAsStringAsync();

            result.EnsureSuccessStatusCode();
            var response = SOAPEnvelope <GetPrescriptionResponseBody> .Deserialize(xml);

            var securedContent = response.Body.GetPrescriptionResponse.SecuredGetPrescriptionResponse.SecuredContent;

            byte[] decrypted;
            using (var decryptor = symKey.CreateDecryptor())
            {
                var payload = Convert.FromBase64String(securedContent);
                decrypted = decryptor.TransformFinalBlock(payload, 0, payload.Length);
            }

            xml = Encoding.UTF8.GetString(decrypted).ClearBadFormat();
            var prescriptionResult = GetPrescriptionForPrescriberResult.Deserialize(xml);
            var kgssResponse       = await _kgssService.GetKeyFromKGSS(prescriptionResult.EncryptionKeyId, assertion);

            var unsealed     = TripleWrapper.Unseal(Convert.FromBase64String(prescriptionResult.Prescription), Convert.FromBase64String(kgssResponse.NewKey));
            var decompressed = Decompress(unsealed);

            return(new GetPrescriptionResult
            {
                Status = prescriptionResult.Status.Code,
                CreationDate = prescriptionResult.CreationDate,
                FeedbackAllowed = prescriptionResult.FeedbackAllowed,
                PatientId = prescriptionResult.PatientId,
                ExpirationDate = prescriptionResult.ExpirationDate,
                Rid = prescriptionResult.Rid,
                KmehrmessageType = Encoding.UTF8.GetString(decompressed).Deserialize <kmehrmessageType>()
            });
        }