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);
            }
        }
        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)
                    {
                        throw new AdalException(AdalError.AuthorityNotInValidList);
                    }
                }
            }
            catch (WebException ex)
            {
                TokenResponse tokenResponse = OAuth2Response.ReadErrorResponse(ex.Response);
                clientMetrics.SetLastError(tokenResponse != null ? tokenResponse.ErrorCodes : null);

                if (tokenResponse.Error == "invalid_instance")
                {
                    throw new AdalServiceException(AdalError.AuthorityNotInValidList, ex);
                }
                else
                {
                    throw new AdalServiceException(
                        AdalError.AuthorityValidationFailed,
                        string.Format(CultureInfo.InvariantCulture, "{0}. {1}: {2}", AdalErrorMessage.AuthorityValidationFailed, tokenResponse.Error, tokenResponse.ErrorDescription),
                        tokenResponse.ErrorCodes,
                        ex);
                }
            }
            finally
            {
                clientMetrics.EndClientMetricsRecord(ClientMetricsEndpointType.InstanceDiscovery, callState);
            }
        }
Exemple #4
0
 public void EndClientMetricsRecord(string endpoint, CallState callState)
 {
     if (callState != null && callState.AuthorityType == AuthorityType.AAD && metricsTimer != null)
     {
         metricsTimer.Stop();
         lastResponseTime  = metricsTimer.ElapsedMilliseconds;
         lastCorrelationId = callState.CorrelationId;
         lastEndpoint      = endpoint;
         if (pendingClientMetrics == null)
         {
             pendingClientMetrics = this;
         }
     }
 }
 public void EndClientMetricsRecord(string endpoint, CallState callState)
 {
     if (callState != null && callState.AuthorityType == AuthorityType.AAD && metricsTimer != null)
     {
         metricsTimer.Stop();
         lastResponseTime = metricsTimer.ElapsedMilliseconds;
         lastCorrelationId = callState.CorrelationId;
         lastEndpoint = endpoint;
         lock (PendingClientMetricsLock)
         {
             if (pendingClientMetrics == null)
             {
                 pendingClientMetrics = this;
             }
         }
     }
 }
Exemple #6
0
        private static void AddClientMetricsHeadersToRequest(IHttpWebRequest request)
        {
            if (pendingClientMetrics != null && NetworkPlugin.RequestCreationHelper.RecordClientMetrics)
            {
                Dictionary <string, string> headers = new Dictionary <string, string>();
                if (pendingClientMetrics.lastError != null)
                {
                    headers[ClientMetricsHeaderLastError] = pendingClientMetrics.lastError;
                }

                headers[ClientMetricsHeaderLastRequest]      = pendingClientMetrics.lastCorrelationId.ToString();
                headers[ClientMetricsHeaderLastResponseTime] = pendingClientMetrics.lastResponseTime.ToString();
                headers[ClientMetricsHeaderLastEndpoint]     = pendingClientMetrics.lastEndpoint;

                HttpHelper.AddHeadersToRequest(request, headers);
                pendingClientMetrics = null;
            }
        }
        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);
        }
        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;
        }
        private static Dictionary <string, string> GetClientMetricsParameters()
        {
            var parameters = new Dictionary <string, string>();

            lock (PendingClientMetricsLock)
            {
                if (pendingClientMetrics != null)
                {
                    if (pendingClientMetrics.lastError != null)
                    {
                        parameters[ClientMetricsHeaderLastError] = pendingClientMetrics.lastError;
                    }

                    parameters[ClientMetricsHeaderLastRequest]      = pendingClientMetrics.lastCorrelationId.ToString();
                    parameters[ClientMetricsHeaderLastResponseTime] = pendingClientMetrics.lastResponseTime.ToString(CultureInfo.CurrentCulture);
                    parameters[ClientMetricsHeaderLastEndpoint]     = pendingClientMetrics.lastEndpoint;

                    pendingClientMetrics = null;
                }
            }

            return(parameters);
        }
        private static void AddClientMetricsHeadersToRequest(IHttpWebRequest request)
        {
            lock (PendingClientMetricsLock)
            {
                if (pendingClientMetrics != null && NetworkPlugin.RequestCreationHelper.RecordClientMetrics)
                {
                    Dictionary<string, string> headers = new Dictionary<string, string>();
                    if (pendingClientMetrics.lastError != null)
                    {
                        headers[ClientMetricsHeaderLastError] = pendingClientMetrics.lastError;
                    }

                    headers[ClientMetricsHeaderLastRequest] = pendingClientMetrics.lastCorrelationId.ToString();
                    headers[ClientMetricsHeaderLastResponseTime] = pendingClientMetrics.lastResponseTime.ToString();
                    headers[ClientMetricsHeaderLastEndpoint] = pendingClientMetrics.lastEndpoint;

                    HttpHelper.AddHeadersToRequest(request, headers);
                    pendingClientMetrics = null;
                }
            }
        }
        private static Dictionary<string, string> GetClientMetricsParameters()
        {
            var parameters = new Dictionary<string, string>();
            lock (PendingClientMetricsLock)
            {
                if (pendingClientMetrics != null)
                {
                    if (pendingClientMetrics.lastError != null)
                    {
                        parameters[ClientMetricsHeaderLastError] = pendingClientMetrics.lastError;
                    }

                    parameters[ClientMetricsHeaderLastRequest] = pendingClientMetrics.lastCorrelationId.ToString();
                    parameters[ClientMetricsHeaderLastResponseTime] = pendingClientMetrics.lastResponseTime.ToString();
                    parameters[ClientMetricsHeaderLastEndpoint] = pendingClientMetrics.lastEndpoint;

                    pendingClientMetrics = null;
                }
            }

            return parameters;
        }
        private async Task <T> GetResponseAsync <T>(string endpointType, bool respondToDeviceAuthChallenge)
        {
            T typedResponse = default(T);
            IHttpWebResponse response;
            ClientMetrics    clientMetrics = new ClientMetrics();

            try
            {
                clientMetrics.BeginClientMetricsRecord(this.CallState);

                if (PlatformPlugin.HttpClientFactory.AddAdditionalHeaders)
                {
                    Dictionary <string, string> clientMetricsHeaders = clientMetrics.GetPreviousRequestRecord(this.CallState);
                    foreach (KeyValuePair <string, string> kvp in clientMetricsHeaders)
                    {
                        this.Client.Headers[kvp.Key] = kvp.Value;
                    }

                    IDictionary <string, string> adalIdHeaders = AdalIdHelper.GetAdalIdParameters();
                    foreach (KeyValuePair <string, string> kvp in adalIdHeaders)
                    {
                        this.Client.Headers[kvp.Key] = kvp.Value;
                    }
                }

                //add pkeyauth header
                this.Client.Headers[DeviceAuthHeaderName] = DeviceAuthHeaderValue;
                using (response = await this.Client.GetResponseAsync())
                {
                    typedResponse = DeserializeResponse <T>(response.ResponseStream);
                    clientMetrics.SetLastError(null);
                }
            }
            catch (HttpRequestWrapperException ex)
            {
                if (!this.isDeviceAuthChallenge(endpointType, ex.WebResponse, respondToDeviceAuthChallenge))
                {
                    AdalServiceException serviceEx;
                    if (ex.WebResponse != null)
                    {
                        TokenResponse tokenResponse = TokenResponse.CreateFromErrorResponse(ex.WebResponse);
                        string[]      errorCodes    = tokenResponse.ErrorCodes ?? new[] { ex.WebResponse.StatusCode.ToString() };
                        serviceEx = new AdalServiceException(tokenResponse.Error, tokenResponse.ErrorDescription,
                                                             errorCodes, ex);
                    }
                    else
                    {
                        serviceEx = new AdalServiceException(AdalError.Unknown, ex);
                    }

                    clientMetrics.SetLastError(serviceEx.ServiceErrorCodes);
                    PlatformPlugin.Logger.Error(CallState, serviceEx);
                    throw serviceEx;
                }
                else
                {
                    response = ex.WebResponse;
                }
            }
            finally
            {
                clientMetrics.EndClientMetricsRecord(endpointType, this.CallState);
            }

            //check for pkeyauth challenge
            if (this.isDeviceAuthChallenge(endpointType, response, respondToDeviceAuthChallenge))
            {
                return(await HandleDeviceAuthChallenge <T>(endpointType, response));
            }

            return(typedResponse);
        }