コード例 #1
0
        /// <summary>
        /// Executes the SOAP request.
        /// </summary>
        /// <param name="authHeader">CrmAuthenticationHeader.</param>
        /// <param name="requestBody">The SOAP request body.</param>
        /// <param name="url">The CRM URL.</param>
        /// <returns>SOAP response.</returns>
        public static XmlDocument ExecuteSoapRequest(CrmAuthenticationHeader authHeader, string requestBody, string url)
        {
            if (!url.EndsWith("/"))
            {
                url += "/";
            }

            StringBuilder xml = new StringBuilder();

            xml.Append("<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://www.w3.org/2005/08/addressing\">");
            xml.Append(authHeader.Header);
            xml.Append(requestBody);
            xml.Append("</s:Envelope>");

            HttpWebRequest request  = (HttpWebRequest)WebRequest.Create(url + "XRMServices/2011/Organization.svc");
            ASCIIEncoding  encoding = new ASCIIEncoding();

            byte[] bytesToWrite = encoding.GetBytes(xml.ToString());
            request.Method        = "POST";
            request.ContentLength = bytesToWrite.Length;
            request.ContentType   = "application/soap+xml; charset=UTF-8";

            Stream newStream = request.GetRequestStream();

            newStream.Write(bytesToWrite, 0, bytesToWrite.Length);
            newStream.Close();

            HttpWebResponse response   = (HttpWebResponse)request.GetResponse();
            Stream          dataStream = response.GetResponseStream();

            if (dataStream != null)
            {
                StreamReader reader = new StreamReader(dataStream);

                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(reader);

                return(xDoc);
            }

            return(null);
        }
コード例 #2
0
        /// <summary>
        /// Executes the SOAP request.
        /// </summary>
        /// <param name="authHeader">CrmAuthenticationHeader.</param>
        /// <param name="requestBody">The SOAP request body.</param>
        /// <param name="url">The CRM URL.</param>
        /// <returns>SOAP response.</returns>
        public static XmlDocument ExecuteSoapRequest(CrmAuthenticationHeader authHeader, string requestBody, string url)
        {
            if (!url.EndsWith("/"))
                url += "/";

            StringBuilder xml = new StringBuilder();
            xml.Append("<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://www.w3.org/2005/08/addressing\">");
            xml.Append(authHeader.Header);
            xml.Append(requestBody);
            xml.Append("</s:Envelope>");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "XRMServices/2011/Organization.svc");
            ASCIIEncoding encoding = new ASCIIEncoding();

            byte[] bytesToWrite = encoding.GetBytes(xml.ToString());
            request.Method = "POST";
            request.ContentLength = bytesToWrite.Length;
            request.ContentType = "application/soap+xml; charset=UTF-8";

            Stream newStream = request.GetRequestStream();
            newStream.Write(bytesToWrite, 0, bytesToWrite.Length);
            newStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            if (dataStream != null)
            {
                StreamReader reader = new StreamReader(dataStream);

                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(reader);

                return xDoc;
            }

            return null;
        }
コード例 #3
0
        private static string CrmWhoAmI(CrmAuthenticationHeader authHeader, string url)
        {
            StringBuilder xml = new StringBuilder();
            xml.Append("<s:Body>");
            xml.Append("<Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\">");
            xml.Append("<request i:type=\"c:WhoAmIRequest\" xmlns:b=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:c=\"http://schemas.microsoft.com/crm/2011/Contracts\">");
            xml.Append("<b:Parameters xmlns:d=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\"/>");
            xml.Append("<b:RequestId i:nil=\"true\"/>");
            xml.Append("<b:RequestName>WhoAmI</b:RequestName>");
            xml.Append("</request>");
            xml.Append("</Execute>");
            xml.Append("</s:Body>");

            XmlDocument xDoc = CrmExecuteSoap.ExecuteSoapRequest(authHeader, xml.ToString(), url);
            if (xDoc == null)
                return null;

            XmlNodeList nodes = xDoc.GetElementsByTagName("b:KeyValuePairOfstringanyType");
            foreach (XmlNode node in nodes)
            {
                if (node.FirstChild.InnerText == "UserId")
                    return node.LastChild.InnerText;
            }

            return null;
        }
コード例 #4
0
        /// <summary>
        /// Gets a CRM Online SOAP header & expiration.
        /// </summary>
        /// <param name="username">Username of a valid CRM user.</param>
        /// <param name="password">Password of a valid CRM user.</param>
        /// <param name="url">The Url of the CRM Online organization (https://org.crm.dynamics.com).</param>
        /// <returns>An object containing the SOAP header and expiration date/time of the header.</returns>
        public CrmAuthenticationHeader GetHeaderOnline(string username, string password, string url)
        {
            if (!url.EndsWith("/"))
                url += "/";

            string urnAddress = GetUrnOnline(url);
            DateTime now = DateTime.Now;

            StringBuilder xml = new StringBuilder();
            xml.Append("<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://www.w3.org/2005/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">");
            xml.Append("<s:Header>");
            xml.Append("<a:Action s:mustUnderstand=\"1\">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action>");
            xml.Append("<a:MessageID>urn:uuid:" + Guid.NewGuid() + "</a:MessageID>");
            xml.Append("<a:ReplyTo>");
            xml.Append("<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>");
            xml.Append("</a:ReplyTo>");
            xml.Append("<a:To s:mustUnderstand=\"1\">https://login.microsoftonline.com/RST2.srf</a:To>");
            xml.Append("<o:Security s:mustUnderstand=\"1\" xmlns:o=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">");
            xml.Append("<u:Timestamp u:Id=\"_0\">");
            xml.Append("<u:Created>" + now.ToUniversalTime().ToString("o") + "</u:Created>");
            xml.Append("<u:Expires>" + now.AddMinutes(60).ToUniversalTime().ToString("o") + "</u:Expires>");
            xml.Append("</u:Timestamp>");
            xml.Append("<o:UsernameToken u:Id=\"uuid-" + Guid.NewGuid() + "-1\">");
            xml.Append("<o:Username>" + username + "</o:Username>");
            xml.Append("<o:Password>" + password + "</o:Password>");
            xml.Append("</o:UsernameToken>");
            xml.Append("</o:Security>");
            xml.Append("</s:Header>");
            xml.Append("<s:Body>");
            xml.Append("<trust:RequestSecurityToken xmlns:trust=\"http://schemas.xmlsoap.org/ws/2005/02/trust\">");
            xml.Append("<wsp:AppliesTo xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\">");
            xml.Append("<a:EndpointReference>");
            xml.Append("<a:Address>urn:" + urnAddress + "</a:Address>");
            xml.Append("</a:EndpointReference>");
            xml.Append("</wsp:AppliesTo>");
            xml.Append("<trust:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</trust:RequestType>");
            xml.Append("</trust:RequestSecurityToken>");
            xml.Append("</s:Body>");
            xml.Append("</s:Envelope>");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://login.microsoftonline.com/RST2.srf");
            ASCIIEncoding encoding = new ASCIIEncoding();

            byte[] bytesToWrite = encoding.GetBytes(xml.ToString());
            request.Method = "POST";
            request.ContentLength = bytesToWrite.Length;
            request.ContentType = "application/soap+xml; charset=UTF-8";

            Stream newStream = request.GetRequestStream();
            newStream.Write(bytesToWrite, 0, bytesToWrite.Length);
            newStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();

            if (dataStream == null)
                return null;

            StreamReader reader = new StreamReader(dataStream);

            XmlDocument x = new XmlDocument();
            x.Load(reader);

            XmlNodeList cipherElements = x.GetElementsByTagName("CipherValue");
            string token1 = cipherElements[0].InnerText;
            string token2 = cipherElements[1].InnerText;

            XmlNodeList keyIdentiferElements = x.GetElementsByTagName("wsse:KeyIdentifier");
            string keyIdentifer = keyIdentiferElements[0].InnerText;

            XmlNodeList tokenExpiresElements = x.GetElementsByTagName("wsu:Expires");
            string tokenExpires = tokenExpiresElements[0].InnerText;

            CrmAuthenticationHeader authHeader = new CrmAuthenticationHeader
            {
                Header = CreateSoapHeaderOnline(url, keyIdentifer, token1, token2),
                Expires = DateTimeOffset.Parse(tokenExpires).UtcDateTime
            };

            return authHeader;
        }
コード例 #5
0
        /// <summary>
        /// Gets a CRM On Premise SOAP header & expiration.
        /// </summary>
        /// <param name="username">Username of a valid CRM user.</param>
        /// <param name="password">Password of a valid CRM user.</param>
        /// <param name="url">The Url of the CRM On Premise (IFD) organization (https://org.domain.com).</param>
        /// <returns>An object containing the SOAP header and expiration date/time of the header.</returns>
        public CrmAuthenticationHeader GetHeaderOnPremise(string username, string password, string url)
        {
            if (!url.EndsWith("/"))
                url += "/";
            string adfsUrl = GetAdfs(url);
            if (adfsUrl == null)
                return null;

            DateTime now = DateTime.Now;
            string urnAddress = url + "XRMServices/2011/Organization.svc";
            string usernamemixed = adfsUrl + "/13/usernamemixed";

            StringBuilder xml = new StringBuilder();
            xml.Append("<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://www.w3.org/2005/08/addressing\">");
            xml.Append("<s:Header>");
            xml.Append("<a:Action s:mustUnderstand=\"1\">http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue</a:Action>");
            xml.Append("<a:MessageID>urn:uuid:" + Guid.NewGuid() + "</a:MessageID>");
            xml.Append("<a:ReplyTo>");
            xml.Append("<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>");
            xml.Append("</a:ReplyTo>");
            xml.Append("<Security s:mustUnderstand=\"1\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">");
            xml.Append("<u:Timestamp  u:Id=\"" + Guid.NewGuid() + "\">");
            xml.Append("<u:Created>" + now.ToUniversalTime().ToString("o") + "</u:Created>");
            xml.Append("<u:Expires>" + now.AddMinutes(60).ToUniversalTime().ToString("o") + "</u:Expires>");
            xml.Append("</u:Timestamp>");
            xml.Append("<UsernameToken u:Id=\"" + Guid.NewGuid() + "\">");
            xml.Append("<Username>" + username + "</Username>");
            xml.Append("<Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">" + password + "</Password>");
            xml.Append("</UsernameToken>");
            xml.Append("</Security>");
            xml.Append("<a:To s:mustUnderstand=\"1\">" + usernamemixed + "</a:To>");
            xml.Append("</s:Header>");
            xml.Append("<s:Body>");
            xml.Append("<trust:RequestSecurityToken xmlns:trust=\"http://docs.oasis-open.org/ws-sx/ws-trust/200512\">");
            xml.Append("<wsp:AppliesTo xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\">");
            xml.Append("<a:EndpointReference>");
            xml.Append("<a:Address>" + urnAddress + "</a:Address>");
            xml.Append("</a:EndpointReference>");
            xml.Append("</wsp:AppliesTo>");
            xml.Append("<trust:RequestType>http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue</trust:RequestType>");
            xml.Append("</trust:RequestSecurityToken>");
            xml.Append("</s:Body>");
            xml.Append("</s:Envelope>");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(usernamemixed);
            ASCIIEncoding encoding = new ASCIIEncoding();

            byte[] bytesToWrite = encoding.GetBytes(xml.ToString());
            request.Method = "POST";
            request.ContentLength = bytesToWrite.Length;
            request.ContentType = "application/soap+xml; charset=UTF-8";

            Stream newStream = request.GetRequestStream();
            newStream.Write(bytesToWrite, 0, bytesToWrite.Length);
            newStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();

            if (dataStream == null)
                return null;

            StreamReader reader = new StreamReader(dataStream);

            XmlDocument x = new XmlDocument();
            x.Load(reader);

            XmlNodeList cipherValue1 = x.GetElementsByTagName("e:CipherValue");
            string token1 = cipherValue1[0].InnerText;

            XmlNodeList cipherValue2 = x.GetElementsByTagName("xenc:CipherValue");
            string token2 = cipherValue2[0].InnerText;

            XmlNodeList keyIdentiferElements = x.GetElementsByTagName("o:KeyIdentifier");
            string keyIdentifer = keyIdentiferElements[0].InnerText;

            XmlNodeList x509IssuerNameElements = x.GetElementsByTagName("X509IssuerName");
            string x509IssuerName = x509IssuerNameElements[0].InnerText;

            XmlNodeList x509SerialNumberElements = x.GetElementsByTagName("X509SerialNumber");
            string x509SerialNumber = x509SerialNumberElements[0].InnerText;

            XmlNodeList binarySecretElements = x.GetElementsByTagName("trust:BinarySecret");
            string binarySecret = binarySecretElements[0].InnerText;

            string created = now.AddMinutes(-1).ToUniversalTime().ToString("o");
            string expires = now.AddMinutes(60).ToUniversalTime().ToString("o");
            string timestamp = "<u:Timestamp xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" u:Id=\"_0\"><u:Created>" + created + "</u:Created><u:Expires>" + expires + "</u:Expires></u:Timestamp>";

            SHA1CryptoServiceProvider sha1Hasher = new SHA1CryptoServiceProvider();
            byte[] hashedDataBytes = sha1Hasher.ComputeHash(Encoding.UTF8.GetBytes(timestamp));
            string digestValue = Convert.ToBase64String(hashedDataBytes);

            string signedInfo = "<SignedInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><CanonicalizationMethod Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"></CanonicalizationMethod><SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#hmac-sha1\"></SignatureMethod><Reference URI=\"#_0\"><Transforms><Transform Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"></Transform></Transforms><DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"></DigestMethod><DigestValue>" + digestValue + "</DigestValue></Reference></SignedInfo>";
            byte[] signedInfoBytes = Encoding.UTF8.GetBytes(signedInfo);
            HMACSHA1 hmac = new HMACSHA1();
            byte[] binarySecretBytes = Convert.FromBase64String(binarySecret);
            hmac.Key = binarySecretBytes;
            byte[] hmacHash = hmac.ComputeHash(signedInfoBytes);
            string signatureValue = Convert.ToBase64String(hmacHash);

            XmlNodeList tokenExpiresElements = x.GetElementsByTagName("wsu:Expires");
            CrmAuthenticationHeader authHeader = new CrmAuthenticationHeader
            {
                Expires =
                    DateTime.ParseExact(tokenExpiresElements[0].InnerText, "yyyy-MM-ddTHH:mm:ss.fffK", null)
                        .ToUniversalTime(),
                Header = CreateSoapHeaderOnPremise(url, keyIdentifer, token1, token2, x509IssuerName,
                    x509SerialNumber, signatureValue, digestValue, created, expires)
            };

            return authHeader;
        }
コード例 #6
0
ファイル: CrmAuth.cs プロジェクト: scdi/CRMBandNotifications
        /// <summary>
        /// Gets a CRM On Premise SOAP header & expiration.
        /// </summary>
        /// <param name="username">Username of a valid CRM user.</param>
        /// <param name="password">Password of a valid CRM user.</param>
        /// <param name="url">The Url of the CRM On Premise (IFD) organization (https://org.domain.com).</param>
        /// <returns>An object containing the SOAP header and expiration date/time of the header.</returns>
        public CrmAuthenticationHeader GetHeaderOnPremise(string username, string password, string url)
        {
            if (!url.EndsWith("/"))
            {
                url += "/";
            }
            string adfsUrl = GetAdfs(url);

            if (adfsUrl == null)
            {
                return(null);
            }

            DateTime now           = DateTime.Now;
            string   urnAddress    = url + "XRMServices/2011/Organization.svc";
            string   usernamemixed = adfsUrl + "/13/usernamemixed";

            StringBuilder xml = new StringBuilder();

            xml.Append("<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://www.w3.org/2005/08/addressing\">");
            xml.Append("<s:Header>");
            xml.Append("<a:Action s:mustUnderstand=\"1\">http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue</a:Action>");
            xml.Append("<a:MessageID>urn:uuid:" + Guid.NewGuid() + "</a:MessageID>");
            xml.Append("<a:ReplyTo>");
            xml.Append("<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>");
            xml.Append("</a:ReplyTo>");
            xml.Append("<Security s:mustUnderstand=\"1\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">");
            xml.Append("<u:Timestamp  u:Id=\"" + Guid.NewGuid() + "\">");
            xml.Append("<u:Created>" + now.ToUniversalTime().ToString("o") + "</u:Created>");
            xml.Append("<u:Expires>" + now.AddMinutes(60).ToUniversalTime().ToString("o") + "</u:Expires>");
            xml.Append("</u:Timestamp>");
            xml.Append("<UsernameToken u:Id=\"" + Guid.NewGuid() + "\">");
            xml.Append("<Username>" + username + "</Username>");
            xml.Append("<Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">" + password + "</Password>");
            xml.Append("</UsernameToken>");
            xml.Append("</Security>");
            xml.Append("<a:To s:mustUnderstand=\"1\">" + usernamemixed + "</a:To>");
            xml.Append("</s:Header>");
            xml.Append("<s:Body>");
            xml.Append("<trust:RequestSecurityToken xmlns:trust=\"http://docs.oasis-open.org/ws-sx/ws-trust/200512\">");
            xml.Append("<wsp:AppliesTo xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\">");
            xml.Append("<a:EndpointReference>");
            xml.Append("<a:Address>" + urnAddress + "</a:Address>");
            xml.Append("</a:EndpointReference>");
            xml.Append("</wsp:AppliesTo>");
            xml.Append("<trust:RequestType>http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue</trust:RequestType>");
            xml.Append("</trust:RequestSecurityToken>");
            xml.Append("</s:Body>");
            xml.Append("</s:Envelope>");

            HttpWebRequest request  = (HttpWebRequest)WebRequest.Create(usernamemixed);
            ASCIIEncoding  encoding = new ASCIIEncoding();

            byte[] bytesToWrite = encoding.GetBytes(xml.ToString());
            request.Method        = "POST";
            request.ContentLength = bytesToWrite.Length;
            request.ContentType   = "application/soap+xml; charset=UTF-8";

            Stream newStream = request.GetRequestStream();

            newStream.Write(bytesToWrite, 0, bytesToWrite.Length);
            newStream.Close();

            HttpWebResponse response   = (HttpWebResponse)request.GetResponse();
            Stream          dataStream = response.GetResponseStream();

            if (dataStream == null)
            {
                return(null);
            }

            StreamReader reader = new StreamReader(dataStream);

            XmlDocument x = new XmlDocument();

            x.Load(reader);

            XmlNodeList cipherValue1 = x.GetElementsByTagName("e:CipherValue");
            string      token1       = cipherValue1[0].InnerText;

            XmlNodeList cipherValue2 = x.GetElementsByTagName("xenc:CipherValue");
            string      token2       = cipherValue2[0].InnerText;

            XmlNodeList keyIdentiferElements = x.GetElementsByTagName("o:KeyIdentifier");
            string      keyIdentifer         = keyIdentiferElements[0].InnerText;

            XmlNodeList x509IssuerNameElements = x.GetElementsByTagName("X509IssuerName");
            string      x509IssuerName         = x509IssuerNameElements[0].InnerText;

            XmlNodeList x509SerialNumberElements = x.GetElementsByTagName("X509SerialNumber");
            string      x509SerialNumber         = x509SerialNumberElements[0].InnerText;

            XmlNodeList binarySecretElements = x.GetElementsByTagName("trust:BinarySecret");
            string      binarySecret         = binarySecretElements[0].InnerText;

            string created   = now.AddMinutes(-1).ToUniversalTime().ToString("o");
            string expires   = now.AddMinutes(60).ToUniversalTime().ToString("o");
            string timestamp = "<u:Timestamp xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" u:Id=\"_0\"><u:Created>" + created + "</u:Created><u:Expires>" + expires + "</u:Expires></u:Timestamp>";

            SHA1CryptoServiceProvider sha1Hasher = new SHA1CryptoServiceProvider();

            byte[] hashedDataBytes = sha1Hasher.ComputeHash(Encoding.UTF8.GetBytes(timestamp));
            string digestValue     = Convert.ToBase64String(hashedDataBytes);

            string signedInfo = "<SignedInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><CanonicalizationMethod Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"></CanonicalizationMethod><SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#hmac-sha1\"></SignatureMethod><Reference URI=\"#_0\"><Transforms><Transform Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"></Transform></Transforms><DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"></DigestMethod><DigestValue>" + digestValue + "</DigestValue></Reference></SignedInfo>";

            byte[]   signedInfoBytes = Encoding.UTF8.GetBytes(signedInfo);
            HMACSHA1 hmac            = new HMACSHA1();

            byte[] binarySecretBytes = Convert.FromBase64String(binarySecret);
            hmac.Key = binarySecretBytes;
            byte[] hmacHash       = hmac.ComputeHash(signedInfoBytes);
            string signatureValue = Convert.ToBase64String(hmacHash);

            XmlNodeList             tokenExpiresElements = x.GetElementsByTagName("wsu:Expires");
            CrmAuthenticationHeader authHeader           = new CrmAuthenticationHeader
            {
                Expires =
                    DateTime.ParseExact(tokenExpiresElements[0].InnerText, "yyyy-MM-ddTHH:mm:ss.fffK", null)
                    .ToUniversalTime(),
                Header = CreateSoapHeaderOnPremise(url, keyIdentifer, token1, token2, x509IssuerName,
                                                   x509SerialNumber, signatureValue, digestValue, created, expires)
            };

            return(authHeader);
        }
コード例 #7
0
ファイル: CrmAuth.cs プロジェクト: scdi/CRMBandNotifications
        /// <summary>
        /// Gets a CRM Online SOAP header & expiration.
        /// </summary>
        /// <param name="username">Username of a valid CRM user.</param>
        /// <param name="password">Password of a valid CRM user.</param>
        /// <param name="url">The Url of the CRM Online organization (https://org.crm.dynamics.com).</param>
        /// <returns>An object containing the SOAP header and expiration date/time of the header.</returns>
        public CrmAuthenticationHeader GetHeaderOnline(string username, string password, string url)
        {
            if (!url.EndsWith("/"))
            {
                url += "/";
            }

            string   urnAddress = GetUrnOnline(url);
            DateTime now        = DateTime.Now;

            StringBuilder xml = new StringBuilder();

            xml.Append("<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://www.w3.org/2005/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">");
            xml.Append("<s:Header>");
            xml.Append("<a:Action s:mustUnderstand=\"1\">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action>");
            xml.Append("<a:MessageID>urn:uuid:" + Guid.NewGuid() + "</a:MessageID>");
            xml.Append("<a:ReplyTo>");
            xml.Append("<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>");
            xml.Append("</a:ReplyTo>");
            xml.Append("<a:To s:mustUnderstand=\"1\">https://login.microsoftonline.com/RST2.srf</a:To>");
            xml.Append("<o:Security s:mustUnderstand=\"1\" xmlns:o=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">");
            xml.Append("<u:Timestamp u:Id=\"_0\">");
            xml.Append("<u:Created>" + now.ToUniversalTime().ToString("o") + "</u:Created>");
            xml.Append("<u:Expires>" + now.AddMinutes(60).ToUniversalTime().ToString("o") + "</u:Expires>");
            xml.Append("</u:Timestamp>");
            xml.Append("<o:UsernameToken u:Id=\"uuid-" + Guid.NewGuid() + "-1\">");
            xml.Append("<o:Username>" + username + "</o:Username>");
            xml.Append("<o:Password>" + password + "</o:Password>");
            xml.Append("</o:UsernameToken>");
            xml.Append("</o:Security>");
            xml.Append("</s:Header>");
            xml.Append("<s:Body>");
            xml.Append("<trust:RequestSecurityToken xmlns:trust=\"http://schemas.xmlsoap.org/ws/2005/02/trust\">");
            xml.Append("<wsp:AppliesTo xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\">");
            xml.Append("<a:EndpointReference>");
            xml.Append("<a:Address>urn:" + urnAddress + "</a:Address>");
            xml.Append("</a:EndpointReference>");
            xml.Append("</wsp:AppliesTo>");
            xml.Append("<trust:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</trust:RequestType>");
            xml.Append("</trust:RequestSecurityToken>");
            xml.Append("</s:Body>");
            xml.Append("</s:Envelope>");

            HttpWebRequest request  = (HttpWebRequest)WebRequest.Create("https://login.microsoftonline.com/RST2.srf");
            ASCIIEncoding  encoding = new ASCIIEncoding();

            byte[] bytesToWrite = encoding.GetBytes(xml.ToString());
            request.Method        = "POST";
            request.ContentLength = bytesToWrite.Length;
            request.ContentType   = "application/soap+xml; charset=UTF-8";

            Stream newStream = request.GetRequestStream();

            newStream.Write(bytesToWrite, 0, bytesToWrite.Length);
            newStream.Close();

            HttpWebResponse response   = (HttpWebResponse)request.GetResponse();
            Stream          dataStream = response.GetResponseStream();

            if (dataStream == null)
            {
                return(null);
            }

            StreamReader reader = new StreamReader(dataStream);

            XmlDocument x = new XmlDocument();

            x.Load(reader);

            XmlNodeList cipherElements = x.GetElementsByTagName("CipherValue");
            string      token1         = cipherElements[0].InnerText;
            string      token2         = cipherElements[1].InnerText;

            XmlNodeList keyIdentiferElements = x.GetElementsByTagName("wsse:KeyIdentifier");
            string      keyIdentifer         = keyIdentiferElements[0].InnerText;

            XmlNodeList tokenExpiresElements = x.GetElementsByTagName("wsu:Expires");
            string      tokenExpires         = tokenExpiresElements[0].InnerText;

            CrmAuthenticationHeader authHeader = new CrmAuthenticationHeader
            {
                Header  = CreateSoapHeaderOnline(url, keyIdentifer, token1, token2),
                Expires = DateTimeOffset.Parse(tokenExpires).UtcDateTime
            };

            return(authHeader);
        }