public Dictionary <string, string> GetPreviousRequestRecord(CallState callState)
        {
            Dictionary <string, string> parameters;

            if (callState != null)
            {
                parameters = GetClientMetricsParameters();
            }
            else
            {
                parameters = new Dictionary <string, string>();
            }

            return(parameters);
        }
 public void EndClientMetricsRecord(string endpoint, CallState callState)
 {
     if (callState != null && metricsTimer != null)
     {
         metricsTimer.Stop();
         lastResponseTime  = metricsTimer.ElapsedMilliseconds;
         lastCorrelationId = callState.CorrelationId;
         lastEndpoint      = endpoint;
         lock (PendingClientMetricsLock)
         {
             if (pendingClientMetrics == null)
             {
                 pendingClientMetrics = this;
             }
         }
     }
 }
        public static Dictionary <string, string> ParseKeyValueList(string input, char delimiter, bool urlDecode,
                                                                    bool lowercaseKeys,
                                                                    CallState callState)
        {
            var response = new Dictionary <string, string>();

            List <string> queryPairs = SplitWithQuotes(input, delimiter);

            foreach (string queryPair in queryPairs)
            {
                List <string> pair = SplitWithQuotes(queryPair, '=');

                if (pair.Count == 2 && !string.IsNullOrWhiteSpace(pair[0]) && !string.IsNullOrWhiteSpace(pair[1]))
                {
                    string key   = pair[0];
                    string value = pair[1];

                    // Url decoding is needed for parsing OAuth response, but not for parsing WWW-Authenticate header in 401 challenge
                    if (urlDecode)
                    {
                        key   = UrlDecode(key);
                        value = UrlDecode(value);
                    }

                    if (lowercaseKeys)
                    {
                        key = key.Trim().ToLower();
                    }

                    value = value.Trim().Trim(new[] { '\"' }).Trim();

                    if (response.ContainsKey(key) && callState != null)
                    {
                        PlatformPlugin.Logger.Warning(callState,
                                                      string.Format(CultureInfo.InvariantCulture,
                                                                    "Key/value pair list contains redundant key '{0}'.", key));
                    }

                    response[key] = value;
                }
            }

            return(response);
        }
        public async Task UpdateFromTemplateAsync(CallState callState)
        {
            if (!this.updatedFromTemplate)
            {
                var    authorityUri = new Uri(this.Authority);
                string host         = authorityUri.Authority;
                string path         = authorityUri.AbsolutePath.Substring(1);
                string tenant       = path.Substring(0, path.IndexOf("/", StringComparison.Ordinal));

                AuthenticatorTemplate matchingTemplate = await AuthenticatorTemplateList.FindMatchingItemAsync(this.ValidateAuthority, host, tenant, callState).ConfigureAwait(false);

                this.AuthorizationUri      = matchingTemplate.AuthorizeEndpoint.Replace("{tenant}", tenant);
                this.DeviceCodeUri         = matchingTemplate.DeviceCodeEndpoint.Replace("{tenant}", tenant);
                this.TokenUri              = matchingTemplate.TokenEndpoint.Replace("{tenant}", tenant);
                this.UserRealmUri          = CanonicalizeUri(matchingTemplate.UserRealmEndpoint);
                this.IsTenantless          = IsTenantLess(this.Authority);
                this.SelfSignedJwtAudience = matchingTemplate.Issuer.Replace("{tenant}", tenant);
                this.updatedFromTemplate   = true;
            }
        }
예제 #5
0
        public static string ReadErrorResponse(XDocument responseDocument, CallState callState)
        {
            string errorMessage = null;

            try
            {
                XElement body = responseDocument.Descendants(XmlNamespace.SoapEnvelope + "Body").FirstOrDefault();

                if (body != null)
                {
                    XElement fault = body.Elements(XmlNamespace.SoapEnvelope + "Fault").FirstOrDefault();
                    if (fault != null)
                    {
                        XElement reason = fault.Elements(XmlNamespace.SoapEnvelope + "Reason").FirstOrDefault();
                        if (reason != null)
                        {
                            XElement text = reason.Elements(XmlNamespace.SoapEnvelope + "Text").FirstOrDefault();
                            if (text != null)
                            {
                                using (var reader = text.CreateReader())
                                {
                                    reader.MoveToContent();
                                    errorMessage = reader.ReadInnerXml();
                                }
                            }
                        }
                    }
                }
            }
            catch (XmlException ex)
            {
                PlatformPlugin.Logger.Error(callState, ex);
                throw new MsalException(MsalError.ParsingWsTrustResponseFailed, ex);
            }

            return(errorMessage);
        }
예제 #6
0
 public abstract void Error(CallState callState, Exception ex,
                            [System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = "");
예제 #7
0
 public abstract void Error(CallState callState, string errorMessage,
                            [System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = "");
예제 #8
0
 public abstract void Warning(CallState callState, string message,
                              [System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = "");
예제 #9
0
        public static async Task <WsTrustAddress> FetchWsTrustAddressFromMexAsync(string federationMetadataUrl, UserAuthType userAuthType, CallState callState)
        {
            XDocument mexDocument = await FetchMexAsync(federationMetadataUrl, callState).ConfigureAwait(false);

            return(ExtractWsTrustAddressFromMex(mexDocument, userAuthType, callState));
        }
 public virtual string GetRedirectUriAsString(Uri redirectUri, CallState callState)
 {
     return(redirectUri.OriginalString);
 }
 public HttpClientWrapper(string uri, CallState callState)
 {
     this.uri       = uri;
     this.Headers   = new Dictionary <string, string>();
     this.CallState = callState;
 }
        internal static string PrepareLogMessage(CallState callState, string classOrComponent, string message)
        {
            string correlationId = (callState != null) ? callState.CorrelationId.ToString() : string.Empty;

            return(string.Format(CultureInfo.CurrentCulture, "{0}: {1} - {2}: {3}", DateTime.UtcNow, correlationId, classOrComponent, message));
        }
 internal abstract void Information(CallState callState, string message, [System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = "");
 public static Dictionary <string, string> ParseKeyValueList(string input, char delimiter, bool urlDecode,
                                                             CallState callState)
 {
     return(ParseKeyValueList(input, delimiter, urlDecode, true, callState));
 }
예제 #15
0
        public static async Task <WsTrustResponse> SendRequestAsync(WsTrustAddress wsTrustAddress, UserCredential credential, CallState callState)
        {
            HttpClientWrapper request = new HttpClientWrapper(wsTrustAddress.Uri.AbsoluteUri, callState);

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

            StringBuilder   messageBuilder = BuildMessage(DefaultAppliesTo, wsTrustAddress, credential);
            WsTrustResponse wstResponse;

            try
            {
                request.BodyParameters = new StringRequestParameters(messageBuilder);
                IHttpWebResponse response = await request.GetResponseAsync().ConfigureAwait(false);

                wstResponse = WsTrustResponse.CreateFromResponse(response.ResponseStream, wsTrustAddress.Version);
            }
            catch (WebException ex)
            {
                PlatformPlugin.Logger.Error(callState, ex);
                string errorMessage;

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

                throw new MsalServiceException(
                          MsalError.FederatedServiceReturnedError,
                          string.Format(MsalErrorMessage.FederatedServiceReturnedErrorTemplate, wsTrustAddress.Uri, errorMessage),
                          null,
                          ex);
            }

            return(wstResponse);
        }
예제 #16
0
        internal static async Task <XDocument> FetchMexAsync(string federationMetadataUrl, CallState callState)
        {
            XDocument mexDocument;

            try
            {
                HttpClientWrapper request = new HttpClientWrapper(federationMetadataUrl, callState);
                using (var response = await request.GetResponseAsync().ConfigureAwait(false))
                {
                    mexDocument = XDocument.Load(response.ResponseStream, LoadOptions.None);
                }
            }
            catch (WebException ex)
            {
                PlatformPlugin.Logger.Error(callState, ex);
                throw new MsalServiceException(MsalError.AccessingWsMetadataExchangeFailed, ex);
            }
            catch (XmlException ex)
            {
                PlatformPlugin.Logger.Error(callState, ex);
                throw new MsalException(MsalError.ParsingWsMetadataExchangeFailed, ex);
            }

            return(mexDocument);
        }
 public MsalHttpClient(string uri, CallState callState)
 {
     this.Client    = new HttpClientWrapper(CheckForExtraQueryParameter(uri), callState);
     this.CallState = callState;
 }
예제 #18
0
        public async Task <AuthenticatorTemplate> FindMatchingItemAsync(bool validateAuthority, string host, string tenant, CallState callState)
        {
            AuthenticatorTemplate matchingAuthenticatorTemplate = null;

            if (validateAuthority)
            {
                matchingAuthenticatorTemplate = this.FirstOrDefault(a => string.Compare(host, a.Host, StringComparison.OrdinalIgnoreCase) == 0);
                if (matchingAuthenticatorTemplate == null)
                {
                    // We only check with the first trusted authority (login.windows.net) for instance discovery
                    await this.First().VerifyAnotherHostByInstanceDiscoveryAsync(host, tenant, callState).ConfigureAwait(false);
                }
            }

            return(matchingAuthenticatorTemplate ?? AuthenticatorTemplate.CreateFromHost(host));
        }
 public async virtual Task <bool> IsUserLocalAsync(CallState callState)
 {
     return(await Task.Factory.StartNew(() => false).ConfigureAwait(false));
 }
예제 #20
0
        internal static async Task <UserRealmDiscoveryResponse> CreateByDiscoveryAsync(string userRealmUri, string userName, CallState callState)
        {
            string userRealmEndpoint = userRealmUri;

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

            PlatformPlugin.Logger.Information(callState, string.Format("Sending user realm discovery request to '{0}'", userRealmEndpoint));

            var client = new MsalHttpClient(userRealmEndpoint, callState)
            {
                Client = { Accept = "application/json" }
            };

            return(await client.GetResponseAsync <UserRealmDiscoveryResponse>(ClientMetricsEndpointType.UserRealmDiscovery).ConfigureAwait(false));
        }
        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);

            try
            {
                var client = new MsalHttpClient(instanceDiscoveryEndpoint, callState);
                InstanceDiscoveryResponse discoveryResponse = await client.GetResponseAsync <InstanceDiscoveryResponse>(ClientMetricsEndpointType.InstanceDiscovery).ConfigureAwait(false);

                if (discoveryResponse.TenantDiscoveryEndpoint == null)
                {
                    throw new MsalException(MsalError.AuthorityNotInValidList);
                }
            }
            catch (MsalServiceException ex)
            {
                PlatformPlugin.Logger.Error(callState, ex);
                throw new MsalException((ex.ErrorCode == "invalid_instance") ? MsalError.AuthorityNotInValidList : MsalError.AuthorityValidationFailed, ex);
            }
        }
예제 #22
0
        internal static WsTrustAddress ExtractWsTrustAddressFromMex(XDocument mexDocument, UserAuthType userAuthType, CallState callState)
        {
            WsTrustAddress address = null;
            MexPolicy      policy  = null;

            try
            {
                Dictionary <string, MexPolicy> policies = ReadPolicies(mexDocument);
                Dictionary <string, MexPolicy> bindings = ReadPolicyBindings(mexDocument, policies);
                SetPolicyEndpointAddresses(mexDocument, bindings);
                Random random = new Random();
                //try ws-trust 1.3 first
                policy = policies.Values.Where(p => p.Url != null && p.AuthType == userAuthType && p.Version == WsTrustVersion.WsTrust13).OrderBy(p => random.Next()).FirstOrDefault() ??
                         policies.Values.Where(p => p.Url != null && p.AuthType == userAuthType).OrderBy(p => random.Next()).FirstOrDefault();

                if (policy != null)
                {
                    address         = new WsTrustAddress();
                    address.Uri     = policy.Url;
                    address.Version = policy.Version;
                }
                else if (userAuthType == UserAuthType.IntegratedAuth)
                {
                    throw new MsalException(MsalError.IntegratedAuthFailed, new MsalException(MsalError.WsTrustEndpointNotFoundInMetadataDocument));
                }
                else
                {
                    throw new MsalException(MsalError.WsTrustEndpointNotFoundInMetadataDocument);
                }
            }
            catch (XmlException ex)
            {
                PlatformPlugin.Logger.Error(callState, ex);
                throw new MsalException(MsalError.ParsingWsMetadataExchangeFailed, ex);
            }

            return(address);
        }