private async Task OnBeforeAccessAsync(TokenCacheNotificationArgs args)
        {
            _logger.Verbose($"OnBeforeAccessAsync - before getting the lock " + _semaphoreSlim.CurrentCount);

            // prevent other threads / background tasks from reading the file
            await _semaphoreSlim.WaitAsync().ConfigureAwait(true);

            _logger.Verbose($"OnBeforeAccessAsync - acquired the lock");

            IStorageFile cacheFile = await ApplicationData.Current.LocalFolder.TryGetItemAsync(CacheFileName) as IStorageFile;

            if (cacheFile != null)
            {
                byte[] decryptedBlob;
                try
                {
                    decryptedBlob = await ReadAndDecryptAsync(cacheFile).ConfigureAwait(true);
                }
                catch (Exception ex)
                {
                    _logger.Error("UWP cache file could not be loaded. Using in-memory cache only.");
                    _logger.ErrorPii(ex);

                    return;
                }

                if (decryptedBlob != null)
                {
                    args.TokenCache.DeserializeMsalV3(decryptedBlob);
                }
            }
        }
コード例 #2
0
        private async Task <IWebTokenRequestResultWrapper> AcquireInteractiveWithoutPickerAsync(
            AuthenticationRequestParameters authenticationRequestParameters,
            Prompt prompt,
            IWamPlugin wamPlugin,
            WebAccountProvider provider,
            WebAccount wamAccount)
        {
            bool isForceLoginPrompt = IsForceLoginPrompt(prompt);

            WebTokenRequest webTokenRequest = await wamPlugin.CreateWebTokenRequestAsync(
                provider,
                authenticationRequestParameters,
                isForceLoginPrompt : isForceLoginPrompt,
                isInteractive : true,
                isAccountInWam : true)
                                              .ConfigureAwait(false);

            if (isForceLoginPrompt &&
                ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 6))
            {
                // this feature works correctly since windows RS4, aka 1803 with the AAD plugin only!
                webTokenRequest.Properties["prompt"] = prompt.PromptValue;
            }

            AddCommonParamsToRequest(authenticationRequestParameters, webTokenRequest);

            try
            {
#if WINDOWS_APP
                // UWP requires being on the UI thread
                await _synchronizationContext;
#endif
                IWebTokenRequestResultWrapper wamResult;
                if (wamAccount != null)
                {
                    wamResult = await _wamProxy.RequestTokenForWindowAsync(
                        _parentHandle,
                        webTokenRequest,
                        wamAccount).ConfigureAwait(false);
                }
                else
                {
                    // default user
                    wamResult = await _wamProxy.RequestTokenForWindowAsync(
                        _parentHandle,
                        webTokenRequest).ConfigureAwait(false);
                }
                return(wamResult);
            }
            catch (Exception ex)
            {
                _logger.ErrorPii(ex);
                throw new MsalServiceException(
                          MsalError.WamInteractiveError,
                          "AcquireTokenInteractive without picker failed. See inner exception for details. ", ex);
            }
        }
コード例 #3
0
        private async Task <IWebTokenRequestResultWrapper> AcquireInteractiveWithWamAccountAsync(
            AuthenticationRequestParameters authenticationRequestParameters,
            Prompt msalPrompt,
            IWamPlugin wamPlugin,
            WebAccountProvider provider,
            WebAccount wamAccount)
        {
            WebTokenRequest webTokenRequest = await wamPlugin.CreateWebTokenRequestAsync(
                provider,
                authenticationRequestParameters,
                isForceLoginPrompt : false,
                isInteractive : true,
                isAccountInWam : true)
                                              .ConfigureAwait(false);

            // because of https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/2476
            string differentAuthority = null;

            if (string.Equals(wamAccount?.WebAccountProvider?.Authority, Constants.OrganizationsTenant) &&
                string.Equals(authenticationRequestParameters.Authority.TenantId, Constants.OrganizationsTenant))
            {
                differentAuthority = authenticationRequestParameters.Authority.GetTenantedAuthority("common");
            }

            WamAdapters.AddMsalParamsToRequest(authenticationRequestParameters, webTokenRequest, differentAuthority);

            try
            {
                IWebTokenRequestResultWrapper wamResult;
                if (wamAccount != null)
                {
                    wamResult = await _wamProxy.RequestTokenForWindowAsync(
                        _parentHandle,
                        webTokenRequest,
                        wamAccount).ConfigureAwait(false);
                }
                else
                {
                    // default user
                    wamResult = await _wamProxy.RequestTokenForWindowAsync(
                        _parentHandle,
                        webTokenRequest).ConfigureAwait(false);
                }
                return(wamResult);
            }
            catch (Exception ex)
            {
                _logger.ErrorPii(ex);
                throw new MsalServiceException(
                          MsalError.WamInteractiveError,
                          "AcquireTokenInteractive without picker failed. See inner exception for details. ", ex);
            }
        }
        private async Task <IWebTokenRequestResultWrapper> AcquireInteractiveWithoutPickerAsync(
            AuthenticationRequestParameters authenticationRequestParameters,
            Prompt msalPrompt,
            IWamPlugin wamPlugin,
            WebAccountProvider provider,
            WebAccount wamAccount)
        {
            bool isForceLoginPrompt = IsForceLoginPrompt(msalPrompt);

            WebTokenRequest webTokenRequest = await wamPlugin.CreateWebTokenRequestAsync(
                provider,
                authenticationRequestParameters,
                isForceLoginPrompt : isForceLoginPrompt,
                isInteractive : true,
                isAccountInWam : true)
                                              .ConfigureAwait(false);

            AddPromptToRequest(msalPrompt, isForceLoginPrompt, webTokenRequest);

            WamAdapters.AddMsalParamsToRequest(authenticationRequestParameters, webTokenRequest);

            try
            {
                IWebTokenRequestResultWrapper wamResult;
                if (wamAccount != null)
                {
                    wamResult = await _wamProxy.RequestTokenForWindowAsync(
                        _parentHandle,
                        webTokenRequest,
                        wamAccount).ConfigureAwait(false);
                }
                else
                {
                    // default user
                    wamResult = await _wamProxy.RequestTokenForWindowAsync(
                        _parentHandle,
                        webTokenRequest).ConfigureAwait(false);
                }
                return(wamResult);
            }
            catch (Exception ex)
            {
                _logger.ErrorPii(ex);
                throw new MsalServiceException(
                          MsalError.WamInteractiveError,
                          "AcquireTokenInteractive without picker failed. See inner exception for details. ", ex);
            }
        }
        private async Task <WebAccountProvider> ShowPickerAsync()
        {
            AccountsSettingsPane retaccountPane = null;

            try
            {
#if WINDOWS_APP
                retaccountPane = AccountsSettingsPane.GetForCurrentView();
                retaccountPane.AccountCommandsRequested += Authenticator_AccountCommandsRequested;
                await AccountsSettingsPane.ShowAddAccountAsync();
#else
                retaccountPane = AccountsSettingsPaneInterop.GetForWindow(_parentHandle);
                retaccountPane.AccountCommandsRequested += Authenticator_AccountCommandsRequested;
                await AccountsSettingsPaneInterop.ShowAddAccountForWindowAsync(_parentHandle);
#endif
                return(_provider);
            }
            catch (Exception e)
            {
                _logger.ErrorPii(e);
                throw;
            }
            finally
            {
                if (retaccountPane != null)
                {
                    retaccountPane.AccountCommandsRequested -= Authenticator_AccountCommandsRequested;
                }
            }
        }
コード例 #6
0
        private void OnBeforeAccess(TokenCacheNotificationArgs args)
        {
            IStorageFile cacheFile = ApplicationData.Current.LocalFolder.TryGetItemAsync(CacheFileName)
                                     .AsTask().GetAwaiter().GetResult() as IStorageFile;


            if (cacheFile != null)
            {
                byte[] decryptedBlob = null;

                try
                {
                    decryptedBlob = ReadAndDecrypt(cacheFile);
                }
                catch (Exception ex)
                {
                    _logger.Error("The UWP cache file could not be decrypted. Corrupted files cannot be restored. Deleting the file.");
                    _logger.ErrorPii(ex);

                    cacheFile.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().GetAwaiter().GetResult();
                    return;
                }

                if (decryptedBlob != null)
                {
                    args.TokenCache.DeserializeMsalV3(decryptedBlob);
                }
            }
        }
        internal static string GetEnrollmentId(ICoreLogger logger)
        {
#if iOS
            var keychainData = NSUserDefaults.StandardUserDefaults.StringForKey(EnrollmentIdKey);
            if (!string.IsNullOrEmpty(keychainData))
            {
                try
                {
                    var enrollmentIDs = JsonConvert.DeserializeObject <EnrollmentIDs>(keychainData);

                    return(enrollmentIDs.EnrollmentIds[0].EnrollmentId);
                }
                catch (JsonException jEx)
                {
                    logger.ErrorPii($"Failed to parse enrollmentID for KeychainData: {keychainData}", string.Empty);
                    logger.ErrorPii(jEx);

                    return(string.Empty);
                }
            }
#endif
            return(string.Empty);
        }
コード例 #8
0
        private async Task ShowPickerForWin32WindowAsync(IntPtr windowHandle)
        {
            AccountsSettingsPane retaccountPane = null;

            try
            {
                retaccountPane = AccountsSettingsPaneInterop.GetForWindow(windowHandle);
                retaccountPane.AccountCommandsRequested += Authenticator_AccountCommandsRequested;
                await AccountsSettingsPaneInterop.ShowAddAccountForWindowAsync(windowHandle);
            }
            catch (Exception ex)
            {
                _logger.ErrorPii(ex);
                throw;
            }
            finally
            {
                if (retaccountPane != null)
                {
                    retaccountPane.AccountCommandsRequested -= Authenticator_AccountCommandsRequested;
                    retaccountPane = null;
                }
            }
        }
        private static string ExtractHost(string httpRequest, ICoreLogger logger)
        {
            var   regex = new Regex(UrlHostRegexp);
            Match match = regex.Match(httpRequest);

            if (!match.Success || match.Groups.Count != 2)
            {
                logger.ErrorPii(
                    "Could not extract the host from the authorization response: " + httpRequest,
                    "Could not extract the host from the authorization response. Enable Pii on to see the request");

                throw new MsalClientException(
                          MsalError.InvalidAuthorizationUri,
                          "Could not extract the host from the authorization response - check Pii enabled logs for details");
            }

            return(match.Groups[1].Value.Trim());
        }
コード例 #10
0
 private void OnStart()
 {
     while (!_disposed)
     {
         try
         {
             if (_eventQueue.TryTake(out var action, _tryTakeTimeout))
             {
                 action.Invoke();
             }
         }
         catch (Exception ex)
         {
             _logger.ErrorPii(ex);
             throw; // TODO: do not throw
         }
     }
 }