Exemple #1
0
        internal void ValidateResponseFromBroker(MsalTokenResponse msalTokenResponse)
        {
            _logger.Info(LogMessages.CheckMsalTokenResponseReturnedFromBroker);
            if (msalTokenResponse.AccessToken != null)
            {
                _logger.Info("Success. Response contains an access token");
                return;
            }

            if (msalTokenResponse.Error != null)
            {
                _logger.Info(
                    LogMessages.ErrorReturnedInBrokerResponse(msalTokenResponse.Error));

                if (msalTokenResponse.Error == BrokerResponseConst.NoTokenFound)
                {
                    throw new MsalUiRequiredException(msalTokenResponse.Error, msalTokenResponse.ErrorDescription);
                }

                throw MsalServiceExceptionFactory.FromBrokerResponse(msalTokenResponse.Error,
                                                                     MsalErrorMessage.BrokerResponseError + msalTokenResponse.ErrorDescription,
                                                                     string.IsNullOrEmpty(msalTokenResponse.SubError) ?
                                                                     MsalError.UnknownBrokerError : msalTokenResponse.SubError,
                                                                     msalTokenResponse.CorrelationId,
                                                                     msalTokenResponse.HttpResponse);
            }

            _logger.Info(LogMessages.UnknownErrorReturnedInBrokerResponse);
            throw new MsalServiceException(MsalError.BrokerResponseReturnedError, MsalErrorMessage.BrokerResponseReturnedError, null);
        }
        private async Task <string> GetRegionAsync(ICoreLogger logger)
        {
            if (!Environment.GetEnvironmentVariable(RegionName).IsNullOrEmpty())
            {
                logger.Info($"[Region discovery] Region: {Environment.GetEnvironmentVariable(RegionName)}");
                return(Environment.GetEnvironmentVariable(RegionName));
            }

            try
            {
                HttpResponse response = await _httpManager.SendGetAsync(_ImdsUri, Headers, logger).ConfigureAwait(false);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new MsalClientException(
                              MsalError.RegionDiscoveryFailed,
                              MsalErrorMessage.RegionDiscoveryFailed);
                }

                LocalImdsResponse localImdsResponse = JsonHelper.DeserializeFromJson <LocalImdsResponse>(response.Body);

                logger.Info($"[Region discovery] Call to local IMDS returned region: {localImdsResponse.location}");
                return(localImdsResponse.location);
            }
            catch (Exception e)
            {
                logger.Info("[Region discovery] Call to local imds failed." + e.Message);
                throw;
            }
        }
        protected override async Task <AuthenticationResult> ExecuteAsync(CancellationToken cancellationToken)
        {
            try
            {
                _logger.Info("Attempting to acquire token using using local cache...");
                return(await _clientStrategy.ExecuteAsync(cancellationToken).ConfigureAwait(false));
            }
            catch (MsalException ex)
            {
                if (ex is MsalUiRequiredException || ex is MsalClientException)
                {
                    var errorCode = ex.ErrorCode;

                    if ((errorCode == MsalError.InvalidGrantError ||
                         errorCode == MsalError.NoTokensFoundError ||
                         errorCode == MsalError.NoAccountForLoginHint) &&
                        AuthenticationRequestParameters.IsBrokerConfigured &&
                        ServiceBundle.PlatformProxy.CanBrokerSupportSilentAuth())
                    {
                        _logger.Info("Failed to acquire a token using local cache. Attempting to use broker instead");
                        return(await _brokerStrategyLazy.Value.ExecuteAsync(cancellationToken).ConfigureAwait(false));
                    }
                }

                throw;
            }
        }
Exemple #4
0
        public string GetProtocolKeyFromHandShakeResult(Bundle bundleResult)
        {
            var negotiatedBrokerProtocalKey = bundleResult?.GetString(BrokerConstants.NegotiatedBPVersionKey);

            if (!string.IsNullOrEmpty(negotiatedBrokerProtocalKey))
            {
                _logger.Info("[Android broker] Using broker protocol version: " + negotiatedBrokerProtocalKey);
                return(negotiatedBrokerProtocalKey);
            }

            dynamic errorResult      = JObject.Parse(bundleResult?.GetString(BrokerConstants.BrokerResultV2));
            string  errorCode        = null;
            string  errorDescription = null;

            if (!string.IsNullOrEmpty(errorResult))
            {
                errorCode = errorResult[BrokerResponseConst.BrokerErrorCode]?.ToString();
                string errorMessage = errorResult[BrokerResponseConst.BrokerErrorMessage]?.ToString();
                errorDescription = $"[Android broker] An error occurred during hand shake with the broker. Error: {errorCode} Error Message: {errorMessage}";
            }
            else
            {
                errorCode        = BrokerConstants.BrokerUnknownErrorCode;
                errorDescription = "[Android broker] An error occurred during hand shake with the broker, no detailed error information was returned. ";
            }

            _logger.Error(errorDescription);
            throw new MsalClientException(errorCode, errorDescription);
        }
        public async Task <IReadOnlyList <WebAccount> > FindAllWebAccountsAsync(WebAccountProvider provider, string clientID)
        {
            using (_logger.LogBlockDuration("WAM:FindAllWebAccountsAsync:"))
            {
                if (_logger.IsLoggingEnabled(LogLevel.Verbose))
                {
                    _logger.VerbosePii(provider.ToLogString(true), provider.ToLogString(false));
                }

                // Win 10 RS3 release and above
                if (!ApiInformation.IsMethodPresent(
                        "Windows.Security.Authentication.Web.Core.WebAuthenticationCoreManager",
                        "FindAllAccountsAsync"))
                {
                    _logger.Info("[WamProxy] FindAllAccountsAsync method does not exist (it was introduced in Win 10 RS3). " +
                                 "Returning 0 broker accounts. ");
                    return(Enumerable.Empty <WebAccount>().ToList());
                }

                FindAllAccountsResult findResult = await WebAuthenticationCoreManager.FindAllAccountsAsync(provider, clientID);

                // This is expected to happen with the MSA provider, which does not allow account listing
                if (findResult.Status != FindAllWebAccountsStatus.Success)
                {
                    var error = findResult.ProviderError;
                    _logger.Info($"[WAM Proxy] WebAuthenticationCoreManager.FindAllAccountsAsync failed " +
                                 $" with error code {error.ErrorCode} error message {error.ErrorMessage} and status {findResult.Status}");

                    return(Enumerable.Empty <WebAccount>().ToList());
                }

                _logger.Info($"[WAM Proxy] FindAllWebAccountsAsync returning {findResult.Accounts.Count()} WAM accounts");
                return(findResult.Accounts);
            }
        }
        private async Task AcquireTokenInteractiveViaBrokerAsync(BrokerRequest brokerRequest)
        {
            using (_logger.LogMethodDuration())
            {
                // onActivityResult will receive the response for this activity.
                // Launching this activity will switch to the broker app.

                _logger.Verbose("Starting Android Broker interactive authentication. ");
                Intent brokerIntent = await _brokerHelper
                                      .GetIntentForInteractiveBrokerRequestAsync(brokerRequest, _parentActivity)
                                      .ConfigureAwait(false);

                if (brokerIntent != null)
                {
                    try
                    {
                        _logger.Info(
                            "Calling activity pid:" + AndroidNative.OS.Process.MyPid()
                            + " tid:" + AndroidNative.OS.Process.MyTid() + "uid:"
                            + AndroidNative.OS.Process.MyUid());

                        _parentActivity.StartActivityForResult(brokerIntent, 1001);
                    }
                    catch (ActivityNotFoundException e)
                    {
                        _logger.ErrorPiiWithPrefix(e, "Unable to get Android activity during interactive broker request. ");
                        throw;
                    }
                }
            }
        }
        private async Task <string> GetImdsUriApiVersionAsync(ICoreLogger logger, Dictionary <string, string> headers)
        {
            Uri imdsErrorUri = new Uri(ImdsEndpoint);

            HttpResponse response = await _httpManager.SendGetAsync(imdsErrorUri, headers, logger).ConfigureAwait(false);

            // When IMDS endpoint is called without the api version query param, bad request response comes back with latest version.
            if (response.StatusCode == HttpStatusCode.BadRequest)
            {
                LocalImdsErrorResponse errorResponse = JsonHelper.DeserializeFromJson <LocalImdsErrorResponse>(response.Body);

                if (errorResponse != null && !errorResponse.NewestVersions.IsNullOrEmpty())
                {
                    logger.Info("[Region discovery] Updated the version for IMDS endpoint to: " + errorResponse.NewestVersions[0]);
                    return(errorResponse.NewestVersions[0]);
                }

                logger.Info("[Region Discovery] The response is empty or does not contain the newest versions.");
            }

            logger.Info($"[Region Discovery] Failed to get the updated version for IMDS endpoint. HttpStatusCode: {response.StatusCode}");

            throw MsalServiceExceptionFactory.FromImdsResponse(
                      MsalError.RegionDiscoveryFailed,
                      MsalErrorMessage.RegionDiscoveryFailed,
                      response);
        }
        public static Dictionary <string, string> CreateClientCredentialBodyParameters(
            ICoreLogger logger,
            ICryptographyManager cryptographyManager,
            ClientCredentialWrapper clientCredential,
            string clientId,
            AuthorityEndpoints endpoints,
            bool sendX5C)
        {
            Dictionary <string, string> parameters = new Dictionary <string, string>();

            if (clientCredential != null)
            {
                if (clientCredential.AuthenticationType == ConfidentialClientAuthenticationType.ClientSecret)
                {
                    parameters[OAuth2Parameter.ClientSecret] = clientCredential.Secret;
                }
                else
                {
                    if ((clientCredential.CachedAssertion == null || clientCredential.ValidTo != 0) && clientCredential.AuthenticationType != ConfidentialClientAuthenticationType.SignedClientAssertion)
                    {
                        if (!ValidateClientAssertion(clientCredential, endpoints, sendX5C))
                        {
                            logger.Info(LogMessages.ClientAssertionDoesNotExistOrNearExpiry);

                            JsonWebToken jwtToken;

                            if (clientCredential.AuthenticationType == ConfidentialClientAuthenticationType.ClientCertificateWithClaims)
                            {
                                jwtToken = new JsonWebToken(cryptographyManager, clientId, endpoints?.SelfSignedJwtAudience, clientCredential.ClaimsToSign, clientCredential.AppendDefaultClaims);
                            }
                            else
                            {
                                jwtToken = new JsonWebToken(cryptographyManager, clientId, endpoints?.SelfSignedJwtAudience);
                            }

                            clientCredential.CachedAssertion = jwtToken.Sign(clientCredential, sendX5C);
                            clientCredential.ValidTo         = jwtToken.ValidTo;
                            clientCredential.ContainsX5C     = sendX5C;
                            clientCredential.Audience        = endpoints?.SelfSignedJwtAudience;
                        }
                        else
                        {
                            logger.Info(LogMessages.ReusingTheUnexpiredClientAssertion);
                        }
                    }

                    parameters[OAuth2Parameter.ClientAssertionType] = OAuth2AssertionType.JwtBearer;

                    if (clientCredential.AuthenticationType == ConfidentialClientAuthenticationType.SignedClientAssertion)
                    {
                        parameters[OAuth2Parameter.ClientAssertion] = clientCredential.SignedAssertion;
                    }
                    else
                    {
                        parameters[OAuth2Parameter.ClientAssertion] = clientCredential.CachedAssertion;
                    }
                }
            }
            return(parameters);
        }
Exemple #9
0
        internal void LogParameters(ICoreLogger logger)
        {
            logger.Info("WebView2Options configured");

            logger.Info($"Title: {Title}");
            logger.InfoPii($"BrowserExecutableFolder: {WebView2BrowserExecutableFolder}", "BrowserExecutableFolder set");
        }
Exemple #10
0
        private async Task <string> FetchMsaPassthroughTransferTokenAsync(
            AuthenticationRequestParameters authenticationRequestParameters,
            WebAccountProvider accountProvider)
        {
            try
            {
                // step 1 - get a response from the MSA provider, just to have a WebAccount
                _logger.Info("WAM MSA-PT: Making initial call to MSA provider");
                WebAccount msaPtWebAccount = await TryFetchWebAccountFromMsaAsync(
                    authenticationRequestParameters,
                    accountProvider).ConfigureAwait(false);

                if (msaPtWebAccount != null)
                {
                    // step 2 - get a trasnfer token
                    _logger.Info("WAM MSA-PT: Getting transfer token");
                    string transferToken = await FetchTransferTokenAsync(
                        accountProvider,
                        msaPtWebAccount,
                        authenticationRequestParameters.AppConfig.ClientId).ConfigureAwait(true);

                    return(transferToken);
                }

                return(null);
            }
            catch (Exception ex)
            {
                _logger.Warning("WAM MSA-PT: Getting a transfer token failed " + ex);
                return(null);
            }
        }
Exemple #11
0
        internal /* internal for test */ void ValidateResponseFromBroker(MsalTokenResponse msalTokenResponse)
        {
            _logger.Info(LogMessages.CheckMsalTokenResponseReturnedFromBroker);
            if (msalTokenResponse.AccessToken != null)
            {
                _logger.Info("Success. Response contains an access token. ");
                return;
            }

            if (msalTokenResponse.Error != null)
            {
                _logger.Info(
                    LogMessages.ErrorReturnedInBrokerResponse(msalTokenResponse.Error));

                if (msalTokenResponse.Error == BrokerResponseConst.AndroidNoTokenFound ||
                    msalTokenResponse.Error == BrokerResponseConst.AndroidNoAccountFound ||
                    msalTokenResponse.Error == BrokerResponseConst.AndroidInvalidRefreshToken)
                {
                    throw new MsalUiRequiredException(msalTokenResponse.Error, msalTokenResponse.ErrorDescription);
                }

                throw MsalServiceExceptionFactory.FromBrokerResponse(msalTokenResponse,
                                                                     MsalErrorMessage.BrokerResponseError + msalTokenResponse.ErrorDescription);
            }

            _logger.Info(LogMessages.UnknownErrorReturnedInBrokerResponse);
            throw new MsalServiceException(MsalError.BrokerResponseReturnedError, MsalErrorMessage.BrokerResponseReturnedError, null);
        }
        private async Task <string> GetRegionAsync(RequestContext requestContext)
        {
            ICoreLogger logger = requestContext.Logger;
            string      region = Environment.GetEnvironmentVariable(RegionName);

            if (!string.IsNullOrEmpty(region))
            {
                logger.Info($"[Region discovery] Region found in environment variable: {region}.");

                LogTelemetryData(region, RegionSource.EnvVariable, requestContext);

                return(region);
            }

            try
            {
                var headers = new Dictionary <string, string>
                {
                    { "Metadata", "true" }
                };

                HttpResponse response = await _httpManager.SendGetAsync(BuildImdsUri(DefaultApiVersion), headers, logger, retry : false, GetCancellationToken(requestContext.UserCancellationToken)).ConfigureAwait(false);

                // A bad request occurs when the version in the IMDS call is no longer supported.
                if (response.StatusCode == HttpStatusCode.BadRequest)
                {
                    string apiVersion = await GetImdsUriApiVersionAsync(logger, headers, requestContext.UserCancellationToken).ConfigureAwait(false);                                                       // Get the latest version

                    response = await _httpManager.SendGetAsync(BuildImdsUri(apiVersion), headers, logger, retry : false, GetCancellationToken(requestContext.UserCancellationToken)).ConfigureAwait(false); // Call again with updated version
                }

                if (response.StatusCode == HttpStatusCode.OK && !response.Body.IsNullOrEmpty())
                {
                    return(response.Body);
                }

                logger.Info($"[Region discovery] Call to local IMDS failed with status code: {response.StatusCode} or an empty response.");

                throw MsalServiceExceptionFactory.FromImdsResponse(
                          MsalError.RegionDiscoveryFailed,
                          MsalErrorMessage.RegionDiscoveryFailed,
                          response);
            }
            catch (MsalServiceException e)
            {
                if (MsalError.RequestTimeout.Equals(e.ErrorCode))
                {
                    throw new MsalServiceException(MsalError.RegionDiscoveryFailed, MsalErrorMessage.RegionDiscoveryFailedWithTimeout, e);
                }

                throw e;
            }
            catch (Exception e)
            {
                logger.Info("[Region discovery] Call to local imds failed. " + e);
                throw new MsalServiceException(MsalError.RegionDiscoveryFailed, MsalErrorMessage.RegionDiscoveryFailed, e);
            }
        }
 /// <inheritdoc />
 public void LogParameters(ICoreLogger logger)
 {
     logger.Info("=== AcquireTokenSilent Parameters ===");
     logger.Info("LoginHint provided: " + !string.IsNullOrEmpty(LoginHint));
     logger.InfoPii(
         "Account provided: " + ((Account != null) ? Account.ToString() : "false"),
         "Account provided: " + (Account != null));
     logger.Info("ForceRefresh: " + ForceRefresh);
 }
Exemple #14
0
        public async Task <Uri> ListenToSingleRequestAndRespondAsync(
            int port,
            Func <Uri, MessageAndHttpCode> responseProducer,
            CancellationToken cancellationToken)
        {
            TestBeforeTopLevelCall?.Invoke();
            cancellationToken.ThrowIfCancellationRequested();

            HttpListener httpListener = null;

            try
            {
                string urlToListenTo = "http://localhost:" + port + "/";

                httpListener = new HttpListener();
                httpListener.Prefixes.Add(urlToListenTo);

                TestBeforeStart?.Invoke();

                httpListener.Start();
                _logger.Info("Listening for authorization code on " + urlToListenTo);

                using (cancellationToken.Register(() =>
                {
                    _logger.Warning("HttpListener stopped because cancellation was requested.");
                    TryStopListening(httpListener);
                }))
                {
                    TestBeforeGetContext?.Invoke();
                    HttpListenerContext context = await httpListener.GetContextAsync()
                                                  .ConfigureAwait(false);

                    cancellationToken.ThrowIfCancellationRequested();

                    Respond(responseProducer, context);
                    _logger.Verbose("HttpListner received a message on " + urlToListenTo);

                    // the request URL should now contain the auth code and pkce
                    return(context.Request.Url);
                }
            }
            // If cancellation is requested before GetContextAsync is called, then either
            // an ObjectDisposedException or an HttpListenerException is thrown.
            // But this is just cancellation...
            catch (Exception ex) when(ex is HttpListenerException || ex is ObjectDisposedException)
            {
                _logger.Info("HttpListenerException - cancellation requested? " + cancellationToken.IsCancellationRequested);
                cancellationToken.ThrowIfCancellationRequested();

                // if cancellation was not requested, propagate original ex
                throw;
            }
            finally
            {
                TryStopListening(httpListener);
            }
        }
        /// <summary>
        /// The algorithm here is much more complex in order to workaround a limitation in the AAD plugin's
        /// handling of guest accounts:
        ///
        /// 1. Read the accounts from WAM.AADPlugin
        /// 2. For each account, we need to find its home_account_id as the one from WAM may not be correct
        /// 3. If we can find a cached account with the same LocalAccountId or UPN, use it
        /// 4. If not, make a simple silent token request and use the client info provided
        /// </summary>
        public async Task <IReadOnlyList <IAccount> > GetAccountsAsync(
            string clientId,
            AuthorityInfo authorityInfo,
            Cache.ICacheSessionManager cacheSessionManager,
            Instance.Discovery.IInstanceDiscoveryManager instanceDiscoveryManager)
        {
            var webAccountProvider = await _webAccountProviderFactory.GetAccountProviderAsync("organizations").ConfigureAwait(false);

            var wamAccounts = await _wamProxy.FindAllWebAccountsAsync(webAccountProvider, clientId).ConfigureAwait(false);

            if (wamAccounts.Count > 0)
            {
                var webAccountEnvs = wamAccounts
                                     .Select(w =>
                {
                    _wamProxy.TryGetAccountProperty(w, "Authority", out string accountAuthority);
                    if (accountAuthority != null)
                    {
                        return((new Uri(accountAuthority)).Host);
                    }
                    else
                    {
                        _logger.WarningPii(
                            $"[WAM AAD Provider] Could not convert the WAM account {w.UserName} (id: {w.Id}) to an MSAL account because the Authority could not be found",
                            $"[WAM AAD Provider] Could not convert the WAM account {w.Id} to an MSAL account because the Authority could not be found");

                        return(null);
                    }
                })
                                     .Where(a => a != null);

                var instanceMetadata = await instanceDiscoveryManager.GetMetadataEntryTryAvoidNetworkAsync(authorityInfo, webAccountEnvs, cacheSessionManager.RequestContext)
                                       .ConfigureAwait(false);

                var accountsFromCache = await cacheSessionManager.GetAccountsAsync().ConfigureAwait(false);

                var msalAccountTasks = wamAccounts
                                       .Select(
                    async webAcc =>
                    await ConvertToMsalAccountOrNullAsync(
                        clientId,
                        webAcc,
                        instanceMetadata,
                        cacheSessionManager,
                        accountsFromCache).ConfigureAwait(false));

                var msalAccounts = (await Task.WhenAll(msalAccountTasks).ConfigureAwait(false)).Where(a => a != null).ToList();

                _logger.Info($"[WAM AAD Provider] GetAccountsAsync converted {msalAccounts.Count} accounts from {wamAccounts.Count} WAM accounts");
                return(msalAccounts);
            }

            _logger.Info("[WAM AAD provider] No accounts found.");
            return(Array.Empty <IAccount>());
        }
        private static byte[] CreateAndStoreBrokerKey(ICoreLogger logger)
        {
            logger.Info("CreateAndStoreBrokerKey - creating a new key");

            byte[] brokerKey;
            byte[] rawBytes;
            using (AesManaged algo = CreateSymmetricAlgorith(null))
            {
                algo.GenerateKey();
                rawBytes = algo.Key;
            }

            NSData byteData = NSData.FromArray(rawBytes);

            var recordToAdd = new SecRecord(SecKind.GenericPassword)
            {
                Generic     = NSData.FromString(iOSBrokerConstants.LocalSettingsContainerName),
                Service     = iOSBrokerConstants.BrokerKeyService,
                Account     = iOSBrokerConstants.BrokerKeyAccount,
                Label       = iOSBrokerConstants.BrokerKeyLabel,
                Comment     = iOSBrokerConstants.BrokerKeyComment,
                Description = iOSBrokerConstants.BrokerKeyStorageDescription,
                ValueData   = byteData
            };

            var result = SecKeyChain.Add(recordToAdd);

            if (result == SecStatusCode.DuplicateItem)
            {
                logger.Info("Could not add the broker key, a key already exists. Trying to delete it first.");
                var recordToRemove = new SecRecord(SecKind.GenericPassword)
                {
                    Service = iOSBrokerConstants.BrokerKeyService,
                    Account = iOSBrokerConstants.BrokerKeyAccount,
                };

                var removeResult = SecKeyChain.Remove(recordToRemove);
                logger.Info("Broker key removal result: " + removeResult);

                result = SecKeyChain.Add(recordToAdd);
                logger.Info("Broker key re-adding result: " + result);
            }

            if (result != SecStatusCode.Success)
            {
                logger.Error("Failed to save the broker key to keychain. Result " + result);
                throw new MsalClientException(
                          MsalError.BrokerKeySaveFailed,
                          MsalErrorMessage.iOSBrokerKeySaveFailed(result.ToString()));
            }

            brokerKey = byteData.ToArray();
            return(brokerKey);
        }
Exemple #17
0
        public async Task <MsalTokenResponse> SendTokenRequestToBrokerAsync()
        {
            if (!Broker.IsBrokerInstalledAndInvokable())
            {
                throw new MsalClientException(MsalError.BrokerApplicationRequired, MsalErrorMessage.AndroidBrokerCannotBeInvoked);
            }

            _logger.Info(LogMessages.CanInvokeBrokerAcquireTokenWithBroker);

            return(await SendAndVerifyResponseAsync().ConfigureAwait(false));
        }
        private async Task <RegionInfo> DiscoverAsync(ICoreLogger logger, CancellationToken requestCancellationToken)
        {
            string region = Environment.GetEnvironmentVariable("REGION_NAME");

            if (ValidateRegion(region, "REGION_NAME env variable", logger)) // this is just to validate the region string
            {
                logger.Info($"[Region discovery] Region found in environment variable: {region}.");
                return(new RegionInfo(region, RegionAutodetectionSource.EnvVariable));
            }

            try
            {
                var headers = new Dictionary <string, string>
                {
                    { "Metadata", "true" }
                };

                Uri imdsUri = BuildImdsUri(DefaultApiVersion);

                HttpResponse response = await _httpManager.SendGetAsync(imdsUri, headers, logger, retry : false, GetCancellationToken(requestCancellationToken))
                                        .ConfigureAwait(false);

                // A bad request occurs when the version in the IMDS call is no longer supported.
                if (response.StatusCode == HttpStatusCode.BadRequest)
                {
                    string apiVersion = await GetImdsUriApiVersionAsync(logger, headers, requestCancellationToken).ConfigureAwait(false); // Get the latest version

                    imdsUri  = BuildImdsUri(apiVersion);
                    response = await _httpManager.SendGetAsync(BuildImdsUri(apiVersion), headers, logger, retry : false, GetCancellationToken(requestCancellationToken))
                               .ConfigureAwait(false); // Call again with updated version
                }

                if (response.StatusCode == HttpStatusCode.OK && !response.Body.IsNullOrEmpty())
                {
                    region = response.Body;

                    if (ValidateRegion(region, $"IMDS call to {imdsUri.AbsoluteUri}", logger))
                    {
                        logger.Info($"[Region discovery] Call to local IMDS succeeded. Region: {region}.");
                        return(new RegionInfo(region, RegionAutodetectionSource.Imds));
                    }
                }
                else
                {
                    logger.Warning($"[Region discovery] Call to local IMDS failed with status code {response.StatusCode} or an empty response.");
                }
            }
            catch (Exception e)
            {
                if (e is MsalServiceException msalEx && MsalError.RequestTimeout.Equals(msalEx?.ErrorCode))
                {
                    logger.Warning($"[Region discovery] Call to local IMDS timed out after {_imdsCallTimeoutMs}.");
                }
        internal void LogParameters(ICoreLogger logger)
        {
            logger.Info("DefaultBrowserOptions configured");

            logger.InfoPii("HtmlMessageSuccess " + HtmlMessageSuccess,
                           "HtmlMessageSuccess? " + !String.IsNullOrEmpty(HtmlMessageSuccess));
            logger.InfoPii("HtmlMessageError " + HtmlMessageError,
                           "HtmlMessageError? " + !String.IsNullOrEmpty(HtmlMessageError));
            logger.InfoPii("BrowserRedirectSuccess " + BrowserRedirectSuccess,
                           "BrowserRedirectSuccess? " + (BrowserRedirectSuccess != null));
            logger.InfoPii("BrowserRedirectError " + BrowserRedirectError,
                           "BrowserRedirectError? " + (BrowserRedirectError != null));
            logger.Info($"HidePrivacyPrompt {iOSHidePrivacyPrompt}");
        }
        public async Task <IEnumerable <IAccount> > GetAccountsAsync(string clientID)
        {
            var webAccountProvider = await _webAccountProviderFactory.GetAccountProviderAsync("organizations").ConfigureAwait(false);

            var webAccounts = await _wamProxy.FindAllWebAccountsAsync(webAccountProvider, clientID).ConfigureAwait(false);

            var msalAccounts = webAccounts
                               .Select(webAcc => ConvertToMsalAccountOrNull(webAcc))
                               .Where(a => a != null)
                               .ToList();

            _logger.Info($"[WAM AAD Provider] GetAccountsAsync converted {webAccounts.Count()} MSAL accounts");
            return(msalAccounts);
        }
Exemple #21
0
 public static ModbusDevices FromFile(string filename)
 {
     logger = new CoreLogger();
     logger?.Info($"Devices are creating for {filename} file");
     myDevices = new ModbusDevices(logger);
     return(myDevices = ParseFile(filename) ? myDevices : ModbusDevices.Empty);
 }
Exemple #22
0
 public void Dispose()
 {
     logger.Info($"ModbusMaster is disposing - {myDevice?.Name}");
     if (myTimer != null)
     {
         myTimer.Stop();
         myTimer.Dispose();
     }
     if (master != null)
     {
         master.Dispose();
     }
     if (tcpClient != null)
     {
         tcpClient.Close();
     }
 }
Exemple #23
0
        public static async Task <IReadOnlyList <WebAccount> > FindAllAccountsAsync(WebAccountProvider provider, string clientID, ICoreLogger logger)
        {
            FindAllAccountsResult findResult = await WebAuthenticationCoreManager.FindAllAccountsAsync(provider, clientID);

            // This is expected to happen with the MSA provider, which does not allow account listing
            if (findResult.Status != FindAllWebAccountsStatus.Success)
            {
                var error = findResult.ProviderError;
                logger.Info($"[WAM Proxy] WebAuthenticationCoreManager.FindAllAccountsAsync failed " +
                            $" with error code {error.ErrorCode} error message {error.ErrorMessage} and status {findResult.Status}");

                return(Enumerable.Empty <WebAccount>().ToList());
            }

            logger.Info($"[WAM Proxy] FindAllWebAccountsAsync returning {findResult.Accounts.Count()} WAM accounts");
            return(findResult.Accounts);
        }
Exemple #24
0
        public async Task <MsalTokenResponse> SendTokenRequestToBrokerAsync()
        {
            if (!Broker.IsBrokerInstalledAndInvokable())
            {
                throw new MsalClientException(MsalError.BrokerApplicationRequired, MsalErrorMessage.AndroidBrokerCannotBeInvoked);
            }

            _logger.Info(LogMessages.CanInvokeBrokerAcquireTokenWithBroker);

            MsalTokenResponse msalTokenResponse =
                await Broker.AcquireTokenSilentAsync(
                    _authenticationRequestParameters,
                    _silentParameters).ConfigureAwait(false);

            ValidateResponseFromBroker(msalTokenResponse);
            return(msalTokenResponse);
        }
        /// <inheritdoc />
        public void LogParameters(ICoreLogger logger)
        {
            var builder = new StringBuilder();

            builder.AppendLine("=== OnBehalfOfParameters ===");
            builder.AppendLine("SendX5C: " + SendX5C);
            logger.Info(builder.ToString());
        }
Exemple #26
0
        internal static byte[] GetRawBrokerKey(ICoreLogger logger)
        {
            byte[]    brokerKey = null;
            SecRecord record    = new SecRecord(SecKind.GenericPassword)
            {
                Account = iOSBrokerConstants.BrokerKeyAccount,
                Service = iOSBrokerConstants.BrokerKeyService
            };

            NSData key = SecKeyChain.QueryAsData(record);

            if (key == null)
            {
                logger.Info("Attempted to query the keychain returned a null NSData key. ");

                AesManaged algo = new AesManaged();
                algo.GenerateKey();
                byte[] rawBytes = algo.Key;
                NSData byteData = NSData.FromArray(rawBytes);
                record = new SecRecord(SecKind.GenericPassword)
                {
                    Generic     = NSData.FromString(iOSBrokerConstants.LocalSettingsContainerName),
                    Service     = iOSBrokerConstants.BrokerKeyService,
                    Account     = iOSBrokerConstants.BrokerKeyAccount,
                    Label       = iOSBrokerConstants.BrokerKeyLabel,
                    Comment     = iOSBrokerConstants.BrokerKeyComment,
                    Description = iOSBrokerConstants.BrokerKeyStorageDescription,
                    ValueData   = byteData
                };

                var result = SecKeyChain.Add(record);
                if (result != SecStatusCode.Success)
                {
                    logger.Info(iOSBrokerConstants.FailedToSaveBrokerKey + result);
                }

                brokerKey = byteData.ToArray();
            }
            else
            {
                brokerKey = key.ToArray();
            }

            return(brokerKey);
        }
Exemple #27
0
        public async Task <MsalTokenResponse> FetchTokensAsync(CancellationToken cancellationToken)
        {
            if (Broker.IsBrokerInstalledAndInvokable())
            {
                _logger.Info(LogMessages.CanInvokeBrokerAcquireTokenWithBroker);
            }
            else
            {
                if (string.IsNullOrEmpty(_optionalBrokerInstallUrl))
                {
                    _logger.Info("Broker is required but not installed. An app uri has not been provided.");
                    return(null);
                }

                _logger.Info(LogMessages.AddBrokerInstallUrlToPayload);
                Broker.HandleInstallUrl(_optionalBrokerInstallUrl);
            }

            var tokenResponse = await Broker.AcquireTokenInteractiveAsync(
                _authenticationRequestParameters,
                _interactiveParameters)
                                .ConfigureAwait(false);

            ValidateResponseFromBroker(tokenResponse);

            return(tokenResponse);
        }
        private async Task <MsalTokenResponse> GetTokenResponseAsync(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (_requestParams.AppConfig.IsBrokerEnabled)
            {
                _logger.Info("Broker is configured. Starting broker flow without knowing the broker installation app link. ");

                MsalTokenResponse brokerTokenResponse = await FetchTokensFromBrokerAsync(
                    null, // we don't have an installation URI yet
                    cancellationToken)
                                                        .ConfigureAwait(false);

                // if we don't get back a result, then continue with the WebUi
                if (brokerTokenResponse != null)
                {
                    _logger.Info("Broker attempt completed successfully. ");
                    Metrics.IncrementTotalAccessTokensFromBroker();
                    return(brokerTokenResponse);
                }

                _logger.Info("Broker attempt did not complete, most likely because the broker is not installed. Attempting to use a browser / web UI. ");
                cancellationToken.ThrowIfCancellationRequested();
            }

            IAuthCodeRequestComponent authorizationFetcher =
                _authCodeRequestComponentOverride ??
                new AuthCodeRequestComponent(
                    _requestParams,
                    _interactiveParameters);

            var result = await authorizationFetcher.FetchAuthCodeAndPkceVerifierAsync(cancellationToken)
                         .ConfigureAwait(false);

            _logger.Info("An authorization code was retrieved from the /authorize endpoint. ");
            AuthorizationResult authResult = result.Item1;
            string authCode         = authResult.Code;
            string pkceCodeVerifier = result.Item2;

            if (BrokerInteractiveRequestComponent.IsBrokerRequiredAuthCode(authCode, out string brokerInstallUri))
            {
                return(await RunBrokerWithInstallUriAsync(brokerInstallUri, cancellationToken).ConfigureAwait(false));
            }

            _logger.Info("Exchanging the auth code for tokens. ");
            var authCodeExchangeComponent =
                _authCodeExchangeComponentOverride ??
                new AuthCodeExchangeComponent(
                    _requestParams,
                    _interactiveParameters,
                    authCode,
                    pkceCodeVerifier,
                    authResult.ClientInfo);

            MsalTokenResponse idpTokenResponse = await authCodeExchangeComponent.FetchTokensAsync(cancellationToken)
                                                 .ConfigureAwait(false);

            Metrics.IncrementTotalAccessTokensFromIdP();
            return(idpTokenResponse);
        }
        public async Task <MsalTokenResponse> FetchTokensAsync(CancellationToken cancellationToken)
        {
            if (Broker.IsBrokerInstalledAndInvokable(_authenticationRequestParameters.AuthorityInfo.AuthorityType))
            {
                _logger.Info(LogMessages.CanInvokeBrokerAcquireTokenWithBroker);
            }
            else
            {
                if (string.IsNullOrEmpty(_optionalBrokerInstallUrl))
                {
                    _logger.Info("Broker is required but is not installed or not available on the current platform. An app URI has not been provided. MSAL will fallback to use a browser.");
                    return(null);
                }

                _logger.Info(LogMessages.AddBrokerInstallUrlToPayload);
                Broker.HandleInstallUrl(_optionalBrokerInstallUrl);
            }

            var tokenResponse = await Broker.AcquireTokenInteractiveAsync(
                _authenticationRequestParameters,
                _interactiveParameters)
                                .ConfigureAwait(false);

            ValidateResponseFromBroker(tokenResponse);

            return(tokenResponse);
        }
Exemple #30
0
        /// <inheritdoc />
        public void LogParameters(ICoreLogger logger)
        {
            var builder = new StringBuilder();

            builder.AppendLine("=== AcquireTokenForClientParameters ===");
            builder.AppendLine("SendX5C: " + SendX5C);
            builder.AppendLine("ForceRefresh: " + ForceRefresh);
            logger.Info(builder.ToString());
        }