public static async Task <T> SendPostRequestAndDeserializeJsonResponseAsync <T>(string uri, RequestParameters requestParameters, CallState callState)
        {
            ClientMetrics clientMetrics = new ClientMetrics();

            try
            {
                IHttpWebRequest request = NetworkPlugin.HttpWebRequestFactory.Create(uri);
                request.ContentType = "application/x-www-form-urlencoded";
                AddCorrelationIdHeadersToRequest(request, callState);
                AdalIdHelper.AddAsHeaders(request);

                clientMetrics.BeginClientMetricsRecord(request, callState);

                SetPostRequest(request, requestParameters, callState);
                using (IHttpWebResponse response = await request.GetResponseSyncOrAsync(callState))
                {
                    VerifyCorrelationIdHeaderInReponse(response, callState);
                    clientMetrics.SetLastError(null);
                    return(DeserializeResponse <T>(response));
                }
            }
            catch (WebException ex)
            {
                TokenResponse tokenResponse = OAuth2Response.ReadErrorResponse(ex.Response);
                clientMetrics.SetLastError(tokenResponse != null ? tokenResponse.ErrorCodes : null);
                throw new AdalServiceException(tokenResponse.Error, tokenResponse.ErrorDescription, tokenResponse.ErrorCodes, ex);
            }
            finally
            {
                clientMetrics.EndClientMetricsRecord(ClientMetricsEndpointType.Token, callState);
            }
        }
        public async Task VerifyAnotherHostByInstanceDiscoveryAsync(string host, string tenant, CallState callState)
        {
            string instanceDiscoveryEndpoint = this.InstanceDiscoveryEndpoint;

            instanceDiscoveryEndpoint += ("?api-version=1.0&authorization_endpoint=" + AuthorizeEndpointTemplate);
            instanceDiscoveryEndpoint  = instanceDiscoveryEndpoint.Replace("{host}", host);
            instanceDiscoveryEndpoint  = instanceDiscoveryEndpoint.Replace("{tenant}", tenant);

            instanceDiscoveryEndpoint = HttpHelper.CheckForExtraQueryParameter(instanceDiscoveryEndpoint);

            ClientMetrics clientMetrics = new ClientMetrics();

            try
            {
                IHttpWebRequest request = NetworkPlugin.HttpWebRequestFactory.Create(instanceDiscoveryEndpoint);
                request.Method = "GET";
                HttpHelper.AddCorrelationIdHeadersToRequest(request, callState);
                AdalIdHelper.AddAsHeaders(request);

                clientMetrics.BeginClientMetricsRecord(request, callState);

                using (var response = await request.GetResponseSyncOrAsync(callState))
                {
                    HttpHelper.VerifyCorrelationIdHeaderInReponse(response, callState);
                    InstanceDiscoveryResponse discoveryResponse = HttpHelper.DeserializeResponse <InstanceDiscoveryResponse>(response);
                    clientMetrics.SetLastError(null);
                    if (discoveryResponse.TenantDiscoveryEndpoint == null)
                    {
                        var ex = new AdalException(AdalError.AuthorityNotInValidList);
                        Logger.LogException(null, ex);
                        throw ex;
                    }
                }
            }
            catch (WebException ex)
            {
                TokenResponse tokenResponse = OAuth2Response.ReadErrorResponse(ex.Response);
                clientMetrics.SetLastError(tokenResponse.ErrorCodes);

                if (tokenResponse.Error == "invalid_instance")
                {
                    var serviceEx = new AdalServiceException(AdalError.AuthorityNotInValidList, ex);
                    Logger.LogException(null, serviceEx);
                    throw serviceEx;
                }
                else
                {
                    var serviceEx = new AdalServiceException(
                        AdalError.AuthorityValidationFailed,
                        string.Format(CultureInfo.InvariantCulture, "{0}. {1}: {2}", AdalErrorMessage.AuthorityValidationFailed, tokenResponse.Error, tokenResponse.ErrorDescription),
                        ex);
                    Logger.LogException(null, serviceEx);
                    throw serviceEx;
                }
            }
            finally
            {
                clientMetrics.EndClientMetricsRecord(ClientMetricsEndpointType.InstanceDiscovery, callState);
            }
        }
Пример #3
0
        internal static async Task <XDocument> FetchMexAsync(string federationMetadataUrl, CallState callState)
        {
            XDocument mexDocument;

            try
            {
                IHttpWebRequest request = PlatformPlugin.HttpWebRequestFactory.Create(federationMetadataUrl);
                request.Method = "GET";
                using (var response = await request.GetResponseSyncOrAsync(callState))
                {
                    mexDocument = XDocument.Load(response.GetResponseStream(), LoadOptions.None);
                }
            }
            catch (WebException ex)
            {
                var serviceEx = new AdalServiceException(AdalError.AccessingWsMetadataExchangeFailed, ex);
                PlatformPlugin.Logger.LogException(callState, serviceEx);
                throw serviceEx;
            }
            catch (XmlException ex)
            {
                var adalEx = new AdalException(AdalError.ParsingWsMetadataExchangeFailed, ex);
                PlatformPlugin.Logger.LogException(callState, adalEx);
                throw adalEx;
            }

            return(mexDocument);
        }
        internal static async Task <XDocument> FetchMexAsync(string federationMetadataUrl, CallState callState)
        {
            XDocument mexDocument;

            try
            {
                IHttpWebRequest request = NetworkPlugin.HttpWebRequestFactory.Create(federationMetadataUrl);
                request.Method      = "GET";
                request.ContentType = "application/soap+xml";
                using (var response = await request.GetResponseSyncOrAsync(callState))
                {
                    mexDocument = XDocument.Load(response.GetResponseStream(), LoadOptions.None);
                }
            }
            catch (WebException ex)
            {
                throw new AdalServiceException(AdalError.AccessingWsMetadataExchangeFailed, ex);
            }
            catch (XmlException ex)
            {
                throw new AdalException(AdalError.ParsingWsMetadataExchangeFailed, ex);
            }

            return(mexDocument);
        }
Пример #5
0
        public static async Task <WsTrustResponse> SendRequestAsync(WsTrustAddress wsTrustAddress, UserCredential credential, CallState callState)
        {
            IHttpWebRequest request = NetworkPlugin.HttpWebRequestFactory.Create(wsTrustAddress.Uri.AbsoluteUri);

            request.ContentType = "application/soap+xml;";
            if (credential.UserAuthType == UserAuthType.IntegratedAuth)
            {
                SetKerberosOption(request);
            }

            StringBuilder messageBuilder = BuildMessage(DefaultAppliesTo, wsTrustAddress, credential);
            string        soapAction     = XmlNamespace.Issue.ToString();

            if (wsTrustAddress.Version == WsTrustVersion.WsTrust2005)
            {
                soapAction = XmlNamespace.Issue2005.ToString();
            }

            Dictionary <string, string> headers = new Dictionary <string, string>
            {
                { "SOAPAction", soapAction }
            };

            WsTrustResponse wstResponse;

            try
            {
                HttpHelper.SetPostRequest(request, new RequestParameters(messageBuilder), callState, headers);
                IHttpWebResponse response = await request.GetResponseSyncOrAsync(callState);

                wstResponse = WsTrustResponse.CreateFromResponse(response.GetResponseStream(), wsTrustAddress.Version);
            }
            catch (WebException ex)
            {
                string errorMessage;

                try
                {
                    XDocument responseDocument = WsTrustResponse.ReadDocumentFromResponse(ex.Response.GetResponseStream());
                    errorMessage = WsTrustResponse.ReadErrorResponse(responseDocument, callState);
                }
                catch (AdalException)
                {
                    errorMessage = "See inner exception for detail.";
                }

                throw new AdalServiceException(
                          AdalError.FederatedServiceReturnedError,
                          string.Format(AdalErrorMessage.FederatedServiceReturnedErrorTemplate, wsTrustAddress.Uri, errorMessage),
                          null,
                          ex);
            }

            return(wstResponse);
        }
Пример #6
0
        private static async Task <AuthenticationParameters> CreateFromResourceUrlCommonAsync(Uri resourceUrl)
        {
            CallState callState = new CallState(Guid.NewGuid(), false);

            if (resourceUrl == null)
            {
                throw new ArgumentNullException("resourceUrl");
            }

            IHttpWebResponse         response = null;
            AuthenticationParameters authParams;

            try
            {
                IHttpWebRequest request = NetworkPlugin.HttpWebRequestFactory.Create(resourceUrl.AbsoluteUri);
                request.ContentType = "application/x-www-form-urlencoded";
                response            = await request.GetResponseSyncOrAsync(callState);

                var ex = new AdalException(AdalError.UnauthorizedResponseExpected);
                Logger.Error(null, ex);
                throw ex;
            }
            catch (WebException ex)
            {
                response = NetworkPlugin.HttpWebRequestFactory.CreateResponse(ex.Response);
                if (response == null)
                {
                    var serviceEx = new AdalServiceException(AdalErrorMessage.UnauthorizedHttpStatusCodeExpected, ex);
                    Logger.Error(null, serviceEx);
                    throw serviceEx;
                }

                authParams = CreateFromUnauthorizedResponseCommon(response);
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }

            return(authParams);
        }
        internal static async Task <UserRealmDiscoveryResponse> CreateByDiscoveryAsync(string userRealmUri, string userName, CallState callState)
        {
            string userRealmEndpoint = userRealmUri;

            userRealmEndpoint += (userName + "?api-version=1.0");

            userRealmEndpoint = HttpHelper.CheckForExtraQueryParameter(userRealmEndpoint);
            Logger.Information(callState, "Sending user realm discovery request to '{0}'", userRealmEndpoint);

            UserRealmDiscoveryResponse userRealmResponse;
            ClientMetrics clientMetrics = new ClientMetrics();

            try
            {
                IHttpWebRequest request = NetworkPlugin.HttpWebRequestFactory.Create(userRealmEndpoint);
                request.Method = "GET";
                request.Accept = "application/json";
                HttpHelper.AddCorrelationIdHeadersToRequest(request, callState);
                AdalIdHelper.AddAsHeaders(request);

                clientMetrics.BeginClientMetricsRecord(request, callState);

                using (var response = await request.GetResponseSyncOrAsync(callState))
                {
                    HttpHelper.VerifyCorrelationIdHeaderInReponse(response, callState);
                    userRealmResponse = HttpHelper.DeserializeResponse <UserRealmDiscoveryResponse>(response);
                    clientMetrics.SetLastError(null);
                }
            }
            catch (WebException ex)
            {
                var serviceException = new AdalServiceException(AdalError.UserRealmDiscoveryFailed, ex);
                clientMetrics.SetLastError(new[] { serviceException.StatusCode.ToString() });
                throw serviceException;
            }
            finally
            {
                clientMetrics.EndClientMetricsRecord(ClientMetricsEndpointType.UserRealmDiscovery, callState);
            }

            return(userRealmResponse);
        }