private string BuildWsSecurityUsingUsernamePassword(string username, string password)
        {
            DateTime utcNow = DateTime.UtcNow;

            return(string.Format(CultureInfo.InvariantCulture, "\r\n            <wsse:UsernameToken wsu:Id=\"user\">\r\n                <wsse:Username>{0}</wsse:Username>\r\n                <wsse:Password>{1}</wsse:Password>\r\n            </wsse:UsernameToken>\r\n            <wsu:Timestamp Id=\"Timestamp\">\r\n                <wsu:Created>{2}</wsu:Created>\r\n                <wsu:Expires>{3}</wsu:Expires>\r\n            </wsu:Timestamp>\r\n", new object[]
            {
                IdcrlUtility.XmlValueEncode(username),
                IdcrlUtility.XmlValueEncode(password),
                utcNow.ToString("o", CultureInfo.InvariantCulture),
                utcNow.AddDays(1.0).ToString("o", CultureInfo.InvariantCulture)
            }));
        }
 private static IdcrlAuth.FederationProviderInfo ParseFederationProviderInfo(XDocument xdoc, string fpDomainName)
 {
     foreach (XElement current in xdoc.Root.Elements("FP"))
     {
         if (current.Attribute("DomainName") != null && string.Equals(current.Attribute("DomainName").Value, fpDomainName, StringComparison.OrdinalIgnoreCase))
         {
             XElement elementAtPath = IdcrlUtility.GetElementAtPath(current, new string[]
             {
                 "URL",
                 "GETUSERREALM"
             });
             XElement elementAtPath2 = IdcrlUtility.GetElementAtPath(current, new string[]
             {
                 "URL",
                 "RST2"
             });
             XElement elementAtPath3 = IdcrlUtility.GetElementAtPath(current, new string[]
             {
                 "URL",
                 "ENTITYID"
             });
             if (elementAtPath == null || elementAtPath2 == null || elementAtPath3 == null)
             {
                 ClientULS.SendTraceTag(3454941u, ClientTraceCategory.Authentication, ClientTraceLevel.High, "Cannot get the user realm service url or security token service url for federation provider {0}", new object[]
                 {
                     fpDomainName
                 });
                 throw IdcrlAuth.CreateIdcrlException(-2147186646);
             }
             ClientULS.SendTraceTag(3454942u, ClientTraceCategory.Authentication, ClientTraceLevel.High, "Find federation provider information for federation provider domain name {0}. UserRealmServiceUrl={1}, SecurityTokenServiceUrl={2}, FederationTokenIssuer={3}", new object[]
             {
                 fpDomainName,
                 elementAtPath.Value,
                 elementAtPath2.Value,
                 elementAtPath3.Value
             });
             return(new IdcrlAuth.FederationProviderInfo
             {
                 UserRealmServiceUrl = elementAtPath.Value,
                 SecurityTokenServiceUrl = elementAtPath2.Value,
                 FederationTokenIssuer = elementAtPath3.Value
             });
         }
     }
     ClientULS.SendTraceTag(3454943u, ClientTraceCategory.Authentication, ClientTraceLevel.High, "Cannot find federation provider information for federation domain {0}", new object[]
     {
         fpDomainName
     });
     throw IdcrlAuth.CreateIdcrlException(-2147186646);
 }
        private static string ParseFPDomainName(XDocument xdoc)
        {
            XElement elementAtPath = IdcrlUtility.GetElementAtPath(xdoc.Root, new string[]
            {
                "FPDOMAINNAME"
            });

            if (elementAtPath == null)
            {
                ClientULS.SendTraceTag(3454940u, ClientTraceCategory.Authentication, ClientTraceLevel.High, "Cannot find FPDOMAINNAME element", new object[0]);
                throw IdcrlAuth.CreateIdcrlException(-2147186646);
            }
            return(elementAtPath.Value);
        }
        private string GetServiceToken(string securityXml, string serviceTarget, string servicePolicy)
        {
            string serviceTokenUrl = this.ServiceTokenUrl;
            string text            = string.Empty;

            if (!string.IsNullOrEmpty(servicePolicy))
            {
                text = string.Format(CultureInfo.InvariantCulture, "<wsp:PolicyReference URI=\"{0}\"></wsp:PolicyReference>", new object[]
                {
                    servicePolicy
                });
            }
            string body = string.Format(CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" xmlns:wst=\"http://schemas.xmlsoap.org/ws/2005/02/trust\">\r\n  <S:Header>\r\n    <wsa:Action S:mustUnderstand=\"1\">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</wsa:Action>\r\n    <wsa:To S:mustUnderstand=\"1\">{0}</wsa:To>\r\n    <ps:AuthInfo xmlns:ps=\"http://schemas.microsoft.com/LiveID/SoapServices/v1\" Id=\"PPAuthInfo\">\r\n      <ps:BinaryVersion>5</ps:BinaryVersion>\r\n      <ps:HostingApp>Managed IDCRL</ps:HostingApp>\r\n    </ps:AuthInfo>\r\n    <wsse:Security>{1}</wsse:Security>\r\n  </S:Header>\r\n  <S:Body>\r\n    <wst:RequestSecurityToken xmlns:wst=\"http://schemas.xmlsoap.org/ws/2005/02/trust\" Id=\"RST0\">\r\n      <wst:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</wst:RequestType>\r\n      <wsp:AppliesTo>\r\n        <wsa:EndpointReference>\r\n          <wsa:Address>{2}</wsa:Address>\r\n        </wsa:EndpointReference>\r\n      </wsp:AppliesTo>\r\n      {3}\r\n    </wst:RequestSecurityToken>\r\n  </S:Body>\r\n</S:Envelope>\r\n", new object[]
            {
                IdcrlUtility.XmlValueEncode(serviceTokenUrl),
                securityXml,
                IdcrlUtility.XmlValueEncode(serviceTarget),
                text
            });
            XDocument xDocument     = this.DoPost(serviceTokenUrl, "application/soap+xml; charset=utf-8", body, new Func <WebException, Exception>(IdcrlAuth.HandleWebException));
            Exception soapException = IdcrlAuth.GetSoapException(xDocument);

            if (soapException != null)
            {
                ClientULS.SendTraceTag(3454926u, ClientTraceCategory.Authentication, ClientTraceLevel.High, "Soap error from {0}. Exception={1}", new object[]
                {
                    serviceTokenUrl,
                    soapException
                });
                throw soapException;
            }
            XElement elementAtPath = IdcrlUtility.GetElementAtPath(xDocument.Root, new string[]
            {
                "{http://www.w3.org/2003/05/soap-envelope}Body",
                "{http://schemas.xmlsoap.org/ws/2005/02/trust}RequestSecurityTokenResponse",
                "{http://schemas.xmlsoap.org/ws/2005/02/trust}RequestedSecurityToken",
                "{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}BinarySecurityToken"
            });

            if (elementAtPath == null)
            {
                ClientULS.SendTraceTag(3454927u, ClientTraceCategory.Authentication, ClientTraceLevel.High, "Cannot get binary security token for from {0}", new object[]
                {
                    serviceTokenUrl
                });
                throw IdcrlAuth.CreateIdcrlException(-2147186656);
            }
            return(elementAtPath.Value);
        }
        private string GetPartnerTicketFromAdfs(string adfsUrl, string username, string password)
        {
            string body = string.Format(CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\" xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" xmlns:wssc=\"http://schemas.xmlsoap.org/ws/2005/02/sc\" xmlns:wst=\"http://schemas.xmlsoap.org/ws/2005/02/trust\">\r\n    <s:Header>\r\n        <wsa:Action s:mustUnderstand=\"1\">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</wsa:Action>\r\n        <wsa:To s:mustUnderstand=\"1\">{0}</wsa:To>\r\n        <wsa:MessageID>{1}</wsa:MessageID>\r\n        <ps:AuthInfo xmlns:ps=\"http://schemas.microsoft.com/Passport/SoapServices/PPCRL\" Id=\"PPAuthInfo\">\r\n            <ps:HostingApp>Managed IDCRL</ps:HostingApp>\r\n            <ps:BinaryVersion>6</ps:BinaryVersion>\r\n            <ps:UIVersion>1</ps:UIVersion>\r\n            <ps:Cookies></ps:Cookies>\r\n            <ps:RequestParams>AQAAAAIAAABsYwQAAAAxMDMz</ps:RequestParams>\r\n        </ps:AuthInfo>\r\n        <wsse:Security>\r\n            <wsse:UsernameToken wsu:Id=\"user\">\r\n                <wsse:Username>{2}</wsse:Username>\r\n                <wsse:Password>{3}</wsse:Password>\r\n            </wsse:UsernameToken>\r\n            <wsu:Timestamp Id=\"Timestamp\">\r\n                <wsu:Created>{4}</wsu:Created>\r\n                <wsu:Expires>{5}</wsu:Expires>\r\n            </wsu:Timestamp>\r\n        </wsse:Security>\r\n    </s:Header>\r\n    <s:Body>\r\n        <wst:RequestSecurityToken Id=\"RST0\">\r\n            <wst:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</wst:RequestType>\r\n            <wsp:AppliesTo>\r\n                <wsa:EndpointReference>\r\n                    <wsa:Address>{6}</wsa:Address>\r\n                </wsa:EndpointReference>\r\n            </wsp:AppliesTo>\r\n            <wst:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</wst:KeyType>\r\n        </wst:RequestSecurityToken>\r\n    </s:Body>\r\n</s:Envelope>", new object[]
            {
                IdcrlUtility.XmlValueEncode(adfsUrl),
                Guid.NewGuid().ToString(),
                IdcrlUtility.XmlValueEncode(username),
                IdcrlUtility.XmlValueEncode(password),
                DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture),
                DateTime.UtcNow.AddMinutes(10.0).ToString("o", CultureInfo.InvariantCulture),
                this.FederationTokenIssuer
            });
            XDocument xDocument     = this.DoPost(adfsUrl, "application/soap+xml; charset=utf-8", body, new Func <WebException, Exception>(IdcrlAuth.HandleWebException));
            Exception soapException = IdcrlAuth.GetSoapException(xDocument);

            if (soapException != null)
            {
                ClientULS.SendTraceTag(3454924u, ClientTraceCategory.Authentication, ClientTraceLevel.High, "SOAP error from {0}. Exception={1}", new object[]
                {
                    adfsUrl,
                    soapException
                });
                throw soapException;
            }
            XElement elementAtPath = IdcrlUtility.GetElementAtPath(xDocument.Root, new string[]
            {
                "{http://www.w3.org/2003/05/soap-envelope}Body",
                "{http://schemas.xmlsoap.org/ws/2005/02/trust}RequestSecurityTokenResponse",
                "{http://schemas.xmlsoap.org/ws/2005/02/trust}RequestedSecurityToken",
                "{urn:oasis:names:tc:SAML:1.0:assertion}Assertion"
            });

            if (elementAtPath == null)
            {
                ClientULS.SendTraceTag(3454925u, ClientTraceCategory.Authentication, ClientTraceLevel.High, "Cannot get security assertion for user {0} from {1}", new object[]
                {
                    username,
                    adfsUrl
                });
                throw IdcrlAuth.CreateIdcrlException(-2147186451);
            }
            return(elementAtPath.ToString(SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces));
        }
Пример #6
0
        private SharePointOnlineAuthenticationProvider.IdcrlHeader GetIdcrlHeader(Uri url, bool alwaysThrowOnFailure, EventHandler <SharePointOnlineCredentialsWebRequestEventArgs> executingWebRequest)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            httpWebRequest.Headers["X-IDCRL_ACCEPTED"] = "t";
            //Edited for .NET Core - Commented out
            //httpWebRequest.AuthenticationLevel = AuthenticationLevel.None;
            if (executingWebRequest != null)
            {
                executingWebRequest(this, new SharePointOnlineCredentialsWebRequestEventArgs(httpWebRequest));
            }
            HttpWebResponse httpWebResponse = null;

            try
            {
                //Edited for .NET Core
                //httpWebResponse = (httpWebRequest.GetResponse() as HttpWebResponse);
                httpWebResponse = httpWebRequest.GetResponseAsync().Result as HttpWebResponse;
            }
            // In .NET Core the Async factor complicates it with an Aggregate exception
            // The first request is always unauthorized and that throws, so the below catch is necessary
            catch (AggregateException aex)
            {
                if (aex.InnerException != null && aex.InnerException.GetType() == typeof(WebException))
                {
                    var ex = aex.InnerException as WebException;
                    ClientULS.SendTraceTag(3991710u, ClientTraceCategory.Authentication, ClientTraceLevel.Medium, "Exception in request. Url={0}, WebException={1}", new object[]
                    {
                        url,
                        ex
                    });
                    httpWebResponse = (ex.Response as HttpWebResponse);
                    if (alwaysThrowOnFailure && (httpWebResponse == null || (httpWebResponse.StatusCode != HttpStatusCode.Forbidden && httpWebResponse.StatusCode != HttpStatusCode.Unauthorized)))
                    {
                        throw;
                    }
                }
            }
            catch (WebException ex)
            {
                ClientULS.SendTraceTag(3991710u, ClientTraceCategory.Authentication, ClientTraceLevel.Medium, "Exception in request. Url={0}, WebException={1}", new object[]
                {
                    url,
                    ex
                });
                httpWebResponse = (ex.Response as HttpWebResponse);
                if (alwaysThrowOnFailure && (httpWebResponse == null || (httpWebResponse.StatusCode != HttpStatusCode.Forbidden && httpWebResponse.StatusCode != HttpStatusCode.Unauthorized)))
                {
                    throw;
                }
            }
            if (httpWebResponse != null)
            {
                string         webResponseHeader = IdcrlUtility.GetWebResponseHeader(httpWebResponse);
                HttpStatusCode statusCode        = httpWebResponse.StatusCode;
                ClientULS.SendTraceTag(4839637u, ClientTraceCategory.Authentication, ClientTraceLevel.Medium, "Response.StatusCode={0}, Headers={1}", new object[]
                {
                    statusCode,
                    webResponseHeader
                });
                string text = httpWebResponse.Headers["X-IDCRL_AUTH_PARAMS_V1"];
                if (string.IsNullOrEmpty(text))
                {
                    text = httpWebResponse.Headers[HttpResponseHeader.WwwAuthenticate];
                }
                //Edited for .NET Core
                httpWebResponse.Dispose();//.Close();
                ClientULS.SendTraceTag(3991712u, ClientTraceCategory.Authentication, ClientTraceLevel.Medium, "IdcrlHeader={0}", new object[]
                {
                    text
                });
                return(this.ParseIdcrlHeader(text, url, statusCode, webResponseHeader, alwaysThrowOnFailure));
            }
            ClientULS.SendTraceTag(3991711u, ClientTraceCategory.Authentication, ClientTraceLevel.High, "Cannot get response for request to {0}", new object[]
            {
                url
            });
            if (alwaysThrowOnFailure)
            {
                throw new ClientRequestException(Resources.GetString("CannotContactSite", new object[]
                {
                    url
                }));
            }
            return(null);
        }
        private static Exception GetSoapException(XDocument xdoc)
        {
            if (IdcrlUtility.GetElementAtPath(xdoc.Root, new string[]
            {
                "{http://www.w3.org/2003/05/soap-envelope}Body",
                "{http://www.w3.org/2003/05/soap-envelope}Fault"
            }) == null)
            {
                return(null);
            }
            XElement elementAtPath = IdcrlUtility.GetElementAtPath(xdoc.Root, new string[]
            {
                "{http://www.w3.org/2003/05/soap-envelope}Body",
                "{http://www.w3.org/2003/05/soap-envelope}Fault",
                "{http://www.w3.org/2003/05/soap-envelope}Code",
                "{http://www.w3.org/2003/05/soap-envelope}Subcode",
                "{http://www.w3.org/2003/05/soap-envelope}Value"
            });
            XElement elementAtPath2 = IdcrlUtility.GetElementAtPath(xdoc.Root, new string[]
            {
                "{http://www.w3.org/2003/05/soap-envelope}Body",
                "{http://www.w3.org/2003/05/soap-envelope}Fault",
                "{http://www.w3.org/2003/05/soap-envelope}Detail",
                "{http://schemas.microsoft.com/Passport/SoapServices/SOAPFault}error",
                "{http://schemas.microsoft.com/Passport/SoapServices/SOAPFault}value"
            });
            XElement elementAtPath3 = IdcrlUtility.GetElementAtPath(xdoc.Root, new string[]
            {
                "{http://www.w3.org/2003/05/soap-envelope}Body",
                "{http://www.w3.org/2003/05/soap-envelope}Fault",
                "{http://www.w3.org/2003/05/soap-envelope}Detail",
                "{http://schemas.microsoft.com/Passport/SoapServices/SOAPFault}error",
                "{http://schemas.microsoft.com/Passport/SoapServices/SOAPFault}internalerror",
                "{http://schemas.microsoft.com/Passport/SoapServices/SOAPFault}text"
            });
            string text = null;

            if (elementAtPath != null)
            {
                text = elementAtPath.Value;
                int num = text.IndexOf(':');
                if (num >= 0)
                {
                    text = text.Substring(num + 1);
                }
            }
            string text2 = null;

            if (elementAtPath2 != null)
            {
                text2 = elementAtPath2.Value;
            }
            string text3 = null;

            if (elementAtPath3 != null)
            {
                text3 = elementAtPath3.Value;
            }
            ClientULS.SendTraceTag(3454935u, ClientTraceCategory.Authentication, ClientTraceLevel.High, "PassportErrorCode={0}, PassportDetailCode={1}, PassportErrorText={2}", new object[]
            {
                text,
                text2,
                text3
            });
            int  num2;
            long num3;

            if (string.IsNullOrEmpty(text2))
            {
                num2 = IdcrlAuth.MapPartnerSoapFault(text);
            }
            else if ((text2.StartsWith("0x", StringComparison.OrdinalIgnoreCase) && long.TryParse(text2.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out num3)) || long.TryParse(text2, NumberStyles.Integer, CultureInfo.InvariantCulture, out num3))
            {
                num2 = (int)num3;
                if (string.Compare(text, "FailedAuthentication", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    num2 = ((num2 == -2147186639) ? num2 : -2147186655);
                }
            }
            else
            {
                num2 = -2147186656;
            }
            return(IdcrlAuth.CreateIdcrlException(num2));
        }