예제 #1
0
        public void ImportExport_ThrowException()
        {
            // Arrange
            var cacheAccessor = NSubstitute.Substitute.For <ICacheAccessor>();
            var cache         = new MockTokenCache();
            var storage       = new MsalCacheStorage(
                _storageCreationPropertiesBuilder.Build(),
                cacheAccessor,
                new TraceSourceLogger(new TraceSource("ts")));
            var helper = new MsalCacheHelper(cache, storage, _logger);

            byte[] dataToSave = Encoding.UTF8.GetBytes("Hello World 2");
            var    ex         = new InvalidCastException();

            cacheAccessor.Read().Throws(ex);

            // Act
            var actualEx = AssertException.Throws <InvalidCastException>(
                () => helper.LoadUnencryptedTokenCache());

            // Assert
            Assert.AreEqual(ex, actualEx);

            // Arrange
            cacheAccessor.WhenForAnyArgs(c => c.Write(default)).Throw(ex);
예제 #2
0
        /// <summary>
        /// Notification that is triggered after token acquisition.
        /// </summary>
        /// <param name="args">Arguments related to the cache item impacted</param>
        public override void AfterAccessNotification(TokenCacheNotificationArgs args)
        {
            MsalCacheHelper cacheStorage = GetMsalCacheStorage();

            args.AssertNotNull(nameof(args));

            try
            {
                if (args.HasStateChanged)
                {
                    cacheStorage.SaveUnencryptedTokenCache(args.TokenCache.SerializeMsalV3());
                }
            }
            catch (Exception)
            {
                cacheStorage.Clear();
                throw;
            }
            finally
            {
                CrossPlatformLock localDispose = cacheLock;
                cacheLock = null;
                localDispose?.Dispose();
            }
        }
        /// <inheritdoc />
        public SharedTokenCacheProvider(IConfiguration config = null, ILogger logger = null)
        {
            _logger = logger;
            _config = config ?? new ConfigurationBuilder().AddEnvironmentVariables().Build();

            const string serviceName = "Microsoft.Developer.IdentityService";
            const string clientId    = "04b07795-8ddb-461a-bbee-02f9e1bf7b46";
            var          storageCreationPropertiesBuilder = new StorageCreationPropertiesBuilder(
                Path.GetFileName(s_cacheFilePath),
                Path.GetDirectoryName(s_cacheFilePath),
                clientId)
                                                            .WithMacKeyChain(serviceName: serviceName, accountName: "MSALCache")
                                                            .WithLinuxKeyring(
                schemaName: "msal.cache",
                collection: "default",
                secretLabel: "MSALCache",
                attribute1: new KeyValuePair <string, string>("MsalClientID", serviceName),
                attribute2: new KeyValuePair <string, string>("MsalClientVersion", "1.0.0.0"));

            var authority = string.Format(CultureInfo.InvariantCulture,
                                          AadAuthority.AadCanonicalAuthorityTemplate,
                                          AadAuthority.DefaultTrustedHost,
                                          "common");

            _app = PublicClientApplicationBuilder
                   .Create(clientId)
                   .WithAuthority(new Uri(authority))
                   .Build();

            var cacheStore = new MsalCacheStorage(storageCreationPropertiesBuilder.Build());

            _cacheHelper = new MsalCacheHelper(_app.UserTokenCache, cacheStore);
            _cacheHelper.RegisterCache(_app.UserTokenCache);
        }
        public void TestInitialize()
        {
            var storageBuilder = new StorageCreationPropertiesBuilder(
                Path.GetFileName(CacheFilePath),
                Path.GetDirectoryName(CacheFilePath));

            storageBuilder = storageBuilder.WithMacKeyChain(
                serviceName: "Microsoft.Developer.IdentityService.Test",
                accountName: "MSALCacheTest");

            // unit tests run on Linux boxes without LibSecret
            storageBuilder.WithLinuxUnprotectedFile();

            // 1. Use MSAL to create an instance of the Public Client Application
            var app = PublicClientApplicationBuilder.Create(ClientId)
                      .Build();

            // 3. Create the high level MsalCacheHelper based on properties and a logger
            _cacheHelper = MsalCacheHelper.CreateAsync(
                storageBuilder.Build(),
                new TraceSource("MSAL.CacheExtension.Test"))
                           .GetAwaiter().GetResult();

            // 4. Let the cache helper handle MSAL's cache
            _cacheHelper.RegisterCache(app.UserTokenCache);
        }
        private async Task RegisterTokenCacheAsync(IPublicClientApplication app)
        {
            Context.Trace.WriteLine(
                "Configuring Microsoft Authentication token cache to instance shared with Microsoft developer tools...");

            if (!PlatformUtils.IsWindows() && !PlatformUtils.IsPosix())
            {
                string osType = PlatformUtils.GetPlatformInformation().OperatingSystemType;
                Context.Trace.WriteLine($"Token cache integration is not supported on {osType}.");
                return;
            }

            // We use the MSAL extension library to provide us consistent cache file access semantics (synchronisation, etc)
            // as other Microsoft developer tools such as the Azure PowerShell CLI.
            MsalCacheHelper helper = null;

            try
            {
                var storageProps = CreateTokenCacheProps(useLinuxFallback: false);
                helper = await MsalCacheHelper.CreateAsync(storageProps);

                // Test that cache access is working correctly
                helper.VerifyPersistence();
            }
            catch (MsalCachePersistenceException ex)
            {
                Context.Streams.Error.WriteLine("warning: cannot persist Microsoft authentication token cache securely!");
                Context.Trace.WriteLine("Cannot persist Microsoft Authentication data securely!");
                Context.Trace.WriteException(ex);

                if (PlatformUtils.IsMacOS())
                {
                    // On macOS sometimes the Keychain returns the "errSecAuthFailed" error - we don't know why
                    // but it appears to be something to do with not being able to access the keychain.
                    // Locking and unlocking (or restarting) often fixes this.
                    Context.Streams.Error.WriteLine(
                        "warning: there is a problem accessing the login Keychain - either manually lock and unlock the " +
                        "login Keychain, or restart the computer to remedy this");
                }
                else if (PlatformUtils.IsLinux())
                {
                    // On Linux the SecretService/keyring might not be available so we must fall-back to a plaintext file.
                    Context.Streams.Error.WriteLine("warning: using plain-text fallback token cache");
                    Context.Trace.WriteLine("Using fall-back plaintext token cache on Linux.");
                    var storageProps = CreateTokenCacheProps(useLinuxFallback: true);
                    helper = await MsalCacheHelper.CreateAsync(storageProps);
                }
            }

            if (helper is null)
            {
                Context.Streams.Error.WriteLine("error: failed to set up Microsoft Authentication token cache!");
                Context.Trace.WriteLine("Failed to integrate with shared token cache!");
            }
            else
            {
                helper.RegisterCache(app.UserTokenCache);
                Context.Trace.WriteLine("Microsoft developer tools token cache configured.");
            }
        }
        private async Task RegisterVisualStudioTokenCacheAsync(IPublicClientApplication app)
        {
            Context.Trace.WriteLine("Configuring Visual Studio token cache...");

            // We currently only support Visual Studio on Windows
            if (PlatformUtils.IsWindows())
            {
                // The Visual Studio MSAL cache is located at "%LocalAppData%\.IdentityService\msal.cache" on Windows.
                // We use the MSAL extension library to provide us consistent cache file access semantics (synchronisation, etc)
                // as Visual Studio itself follows, as well as other Microsoft developer tools such as the Azure PowerShell CLI.
                const string cacheFileName  = "msal.cache";
                string       appData        = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                string       cacheDirectory = Path.Combine(appData, ".IdentityService");

                var storageProps = new StorageCreationPropertiesBuilder(cacheFileName, cacheDirectory, app.AppConfig.ClientId).Build();

                var helper = await MsalCacheHelper.CreateAsync(storageProps);

                helper.RegisterCache(app.UserTokenCache);

                Context.Trace.WriteLine("Visual Studio token cache configured.");
            }
            else
            {
                string osType = PlatformUtils.GetPlatformInformation().OperatingSystemType;
                Context.Trace.WriteLine($"Visual Studio token cache integration is not supported on {osType}.");
            }
        }
예제 #7
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            // Initialize services that you need before app activation
            await InitializeAsync();

            // https://aka.ms/msal-net-token-cache-serialization
            // this generates a file-system safe directory name to stick the cache in - or use something like Resources.AppDisplayName
            // should also consider this root dir for other configuration data
            var safeAppDirectoryName      = System.IO.Path.GetInvalidFileNameChars().Aggregate(typeof(App).Assembly.GetName().Name, (current, c) => current.Replace(c, '-'));
            var rootCacheDirectory        = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), safeAppDirectoryName, _config.IdentityCacheDirectoryName);
            var storageCreationProperties = new StorageCreationPropertiesBuilder(_config.IdentityCacheFileName, rootCacheDirectory, _config.IdentityClientId).Build();
            var cacheHelper = await MsalCacheHelper.CreateAsync(storageCreationProperties).ConfigureAwait(false);

            _identityService.InitializeWithAadAndPersonalMsAccounts(_config.IdentityClientId, "http://localhost", cacheHelper);
            var silentLoginSuccess = await _identityService.AcquireTokenSilentAsync();

            if (!silentLoginSuccess || !_identityService.IsAuthorized())
            {
                _logInWindow = _serviceProvider.GetService(typeof(ILogInWindow)) as ILogInWindow;
                _logInWindow.ShowWindow();
                await StartupAsync();

                return;
            }

            _shellWindow = _serviceProvider.GetService(typeof(IShellWindow)) as IShellWindow;
            _navigationService.Initialize(_shellWindow.GetNavigationFrame());
            _shellWindow.ShowWindow();
            _navigationService.NavigateTo(typeof(MainViewModel).FullName);

            // Tasks after activation
            await StartupAsync();
        }
        private async Task InitializeAsync()
        {
            ConfidentialClientApplicationBuilder confClientBuilder = ConfidentialClientApplicationBuilder.Create(_options.ClientId).WithAuthority(_options.AuthorityHost.AbsoluteUri, _options.TenantId).WithHttpClientFactory(new HttpPipelineClientFactory(_options.Pipeline.HttpPipeline));

            if (_options.Secret != null)
            {
                confClientBuilder.WithClientSecret(_options.Secret);
            }

            if (_options.CertificateProvider != null)
            {
                X509Certificate2 clientCertificate = await _options.CertificateProvider.GetCertificateAsync(true, default).ConfigureAwait(false);

                confClientBuilder.WithCertificate(clientCertificate);
            }

            _client = confClientBuilder.Build();

            if (_options.AttachSharedCache)
            {
                StorageCreationProperties storageProperties = new StorageCreationPropertiesBuilder(Constants.DefaultMsalTokenCacheName, Constants.DefaultMsalTokenCacheDirectory, _options.ClientId)
                                                              .WithMacKeyChain(Constants.DefaultMsalTokenCacheKeychainService, Constants.DefaultMsalTokenCacheKeychainAccount)
                                                              .WithLinuxKeyring(Constants.DefaultMsalTokenCacheKeyringSchema, Constants.DefaultMsalTokenCacheKeyringCollection, Constants.DefaultMsalTokenCacheKeyringLabel, Constants.DefaultMsaltokenCacheKeyringAttribute1, Constants.DefaultMsaltokenCacheKeyringAttribute2)
                                                              .Build();

                MsalCacheHelper cacheHelper = await MsalCacheHelper.CreateAsync(storageProperties).ConfigureAwait(false);

                cacheHelper.RegisterCache(_client.UserTokenCache);
            }
        }
예제 #9
0
        public static IPublicClientApplication CreatePublicClient(
            string authority   = null,
            string clientId    = null,
            string redirectUri = null,
            string tenantId    = null)
        {
            PublicClientApplicationBuilder builder = PublicClientApplicationBuilder.Create(clientId);

            if (!string.IsNullOrEmpty(authority))
            {
                builder = builder.WithAuthority(authority);
            }

            if (!string.IsNullOrEmpty(redirectUri))
            {
                builder = builder.WithRedirectUri(redirectUri);
            }

            if (!string.IsNullOrEmpty(tenantId))
            {
                builder = builder.WithTenantId(tenantId);
            }

            IPublicClientApplication client = builder.WithLogging(
                DebugLoggingMethod,
                LogLevel.Info,
                enablePiiLogging: false,
                enableDefaultPlatformLogging: true).Build();
            MsalCacheHelper cacheHelper = InitializeCacheHelper(clientId);

            cacheHelper.RegisterCache(client.UserTokenCache);

            return(client);
        }
        public async Task <AcquireTokenResult> AcquireTokenAsync()
        {
            var app = PublicClientApplicationBuilder.Create(_clientId).WithTenantId(_tenantId).WithDefaultRedirectUri().Build();

            var storageCreationProperties = new StorageCreationPropertiesBuilder("tokenCache.dat", ".", _clientId).Build();

            (await MsalCacheHelper.CreateAsync(storageCreationProperties)).RegisterCache(app.UserTokenCache);
            var account = await GetAccountAsync(app);

            AuthenticationResult authenticationResult;

            try
            {
                authenticationResult = await app.AcquireTokenSilent(_scopes, account).ExecuteAsync();
            }
            catch (MsalUiRequiredException)
            {
                authenticationResult = await app.AcquireTokenWithDeviceCode(_scopes, deviceCodeResult =>
                {
                    Console.WriteLine(deviceCodeResult.Message);
                    return(deviceCodeResult.VerificationUrl == null ? Task.CompletedTask : OpenBrowserAsync(deviceCodeResult.VerificationUrl));
                }).ExecuteAsync();
            }

            return(new AcquireTokenResult(authenticationResult.AccessToken, ExtractObjectId(authenticationResult.IdToken)));
        }
예제 #11
0
        private static MsalCacheHelper CreateCacheHelperAsync(string clientId)
        {
            StorageCreationProperties storageProperties;

            try
            {
                storageProperties =
                    new StorageCreationPropertiesBuilder(
                        "cache.plaintext",
                        System.AppContext.BaseDirectory,
                        clientId)
                    .WithLinuxUnprotectedFile()
                    .Build();

                var cacheHelper = MsalCacheHelper.CreateAsync(storageProperties).Result;
                return(cacheHelper);
            }
            catch (MsalCachePersistenceException e)
            {
                storageProperties =
                    new StorageCreationPropertiesBuilder(
                        "cache.plaintext",
                        System.AppContext.BaseDirectory,
                        clientId)
                    .WithLinuxUnprotectedFile()
                    .Build();

                var cacheHelper = MsalCacheHelper.CreateAsync(storageProperties).Result;

                cacheHelper.VerifyPersistence();

                return(cacheHelper);
            }
        }
예제 #12
0
 private void ConfigureCache(MsalCacheHelper cacheHelper)
 {
     if (cacheHelper != null)
     {
         // https://aka.ms/msal-net-token-cache-serialization
         cacheHelper.RegisterCache(_client.UserTokenCache);
     }
 }
예제 #13
0
        internal override async Task RegisterCache(bool async, ITokenCache tokenCache, CancellationToken cancellationToken)
        {
            MsalCacheHelper cacheHelper = await GetCacheHelperAsync(async, cancellationToken).ConfigureAwait(false);

            cacheHelper.RegisterCache(tokenCache);

            await base.RegisterCache(async, tokenCache, cancellationToken).ConfigureAwait(false);
        }
예제 #14
0
        private static async ValueTask <MsalCacheHelper> CreateCacheHelper(StorageCreationProperties storageProperties, bool async)
        {
            return(async
                ? await MsalCacheHelper.CreateAsync(storageProperties).ConfigureAwait(false)
#pragma warning disable AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead.
                : MsalCacheHelper.CreateAsync(storageProperties).GetAwaiter().GetResult());

#pragma warning restore AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead.
        }
예제 #15
0
        private static async Task <MsalCacheHelper> GetProtectedCacheHelperAsync(bool async, string name)
        {
            StorageCreationProperties storageProperties = new StorageCreationPropertiesBuilder(name, Constants.DefaultMsalTokenCacheDirectory, s_msalCacheClientId)
                                                          .WithMacKeyChain(Constants.DefaultMsalTokenCacheKeychainService, name)
                                                          .WithLinuxKeyring(Constants.DefaultMsalTokenCacheKeyringSchema, Constants.DefaultMsalTokenCacheKeyringCollection, name, Constants.DefaultMsaltokenCacheKeyringAttribute1, Constants.DefaultMsaltokenCacheKeyringAttribute2)
                                                          .Build();

            MsalCacheHelper cacheHelper = await CreateCacheHelper(async, storageProperties).ConfigureAwait(false);

            return(cacheHelper);
        }
예제 #16
0
        private static async Task <MsalCacheHelper> GetFallbackCacheHelperAsync(bool async, string name)
        {
            StorageCreationProperties storageProperties = new StorageCreationPropertiesBuilder(name, Constants.DefaultMsalTokenCacheDirectory, s_msalCacheClientId)
                                                          .WithMacKeyChain(Constants.DefaultMsalTokenCacheKeychainService, name)
                                                          .WithLinuxUnprotectedFile()
                                                          .Build();

            MsalCacheHelper cacheHelper = await CreateCacheHelper(async, storageProperties).ConfigureAwait(false);

            return(cacheHelper);
        }
        public MicrosoftAuthentication(TeamsPresencePublisherOptions options)
        {
            var storageProperties =
                new StorageCreationPropertiesBuilder("TeamsPresencePublisher.msalcache.bin", options.CacheFolder, ClientId)
                .Build();

            _msalCacheHelper = MsalCacheHelper.CreateAsync(storageProperties).GetAwaiter().GetResult();

            _publicClientApplication = BuildPublicClientApplication();
            AuthProvider             = new InteractiveAuthenticationProvider(_publicClientApplication, s_scopes);
        }
예제 #18
0
        /// <summary>
        /// Calls MSAL to get authentication token with AAD.
        /// </summary>
        /// <returns></returns>
        /// <remarks>https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/Acquiring-tokens-interactively</remarks>
        public async Task <VssCredentials> CreateVssCredentialsWithAadAsync()
        {
            // 1. Configuration
            var app = PublicClientApplicationBuilder
                      .Create(VsoAadConstants.Client)
                      .WithTenantId(VsoAadConstants.MicrosoftTenantId)
                      .WithRedirectUri(VsoAadConstants.RedirectUri)
                      .Build();

            // 2. Token cache
            // https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-net-token-cache-serialization?tabs=desktop
            // https://github.com/AzureAD/microsoft-authentication-extensions-for-dotnet/wiki/Cross-platform-Token-Cache
            var storageProperties = new StorageCreationPropertiesBuilder(m_tokenCacheFileName, m_tokenCacheDirectory).Build();
            var cacheHelper       = await MsalCacheHelper.CreateAsync(storageProperties);

            cacheHelper.RegisterCache(app.UserTokenCache);

            // 3. Try silent authentication
            var accounts = await app.GetAccountsAsync();

            var scopes = new string[] { VsoAadConstants.Scope };
            AuthenticationResult result = null;

            try
            {
                result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
                         .ExecuteAsync();

                m_logger("[VssCredentialsFactory] Successfully acquired authentication token through silent AAD authentication.");
            }
            catch (MsalUiRequiredException)
            {
                // 4. Interactive Authentication
                m_logger("[VssCredentialsFactory] Unable to acquire authentication token through silent AAD authentication.");
                // On Windows, we can try Integrated Windows Authentication which will fallback to interactive auth if that fails
                result = OperatingSystemHelper.IsWindowsOS
                    ? await CreateVssCredentialsWithAadForWindowsAsync(app, scopes)
                    : await CreateVssCredentialsWithAadInteractiveAsync(app, scopes);
            }
            catch (Exception ex)
            {
                m_logger($"[VssCredentialsFactory] Unable to acquire credentials with AAD with the following exception: '{ex}'");
            }

            if (result == null)
            {
                // Something went wrong during AAD auth, return null
                m_logger($"[VssCredentialsFactory] Unable to acquire AAD token.");
                return(new VssAadCredential());
            }

            return(new VssAadCredential(new VssAadToken(VsoAadConstants.TokenType, result.AccessToken)));
        }
예제 #19
0
        private static async Task LoginWithMsalAsync(string[] args)
        {
            try
            {
                string resource      = args[0];
                string tenant        = args[1];
                Uri    baseAuthority = new Uri(args[2]);
#pragma warning disable CA1305 // Specify IFormatProvider
                bool validateAuthority = Convert.ToBoolean(args[3]);
#pragma warning restore CA1305 // Specify IFormatProvider
                string clientId       = args[4];
                string cacheFileName  = args[5];
                string cacheDirectory = Path.Combine(MsalCacheHelper.UserRootDirectory, args[6]);

                string serviceName = null;
                string accountName = null;

                if (args.Length > 7)
                {
                    serviceName = args[7];
                    accountName = args[8];
                }

                (var scopes, var app, var helper) = await Utilities.GetPublicClientAsync(
                    resource,
                    tenant,
                    baseAuthority,
                    validateAuthority,
                    clientId,
                    cacheFileName,
                    cacheDirectory,
                    serviceName,
                    accountName
                    ).ConfigureAwait(false);

                if (s_helper == null)
                {
                    s_helper = helper;
                    s_helper.CacheChanged += (s, e) =>
                    {
                        Console.WriteLine($"Cache Changed, Added: {e.AccountsAdded.Count()} Removed: {e.AccountsRemoved.Count()}");
                    };
                }

                var builder    = app.AcquireTokenWithDeviceCode(scopes, Utilities.DeviceCodeCallbackAsync);
                var authResult = await builder.ExecuteAsync().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error logging in with Msal: {ex}");
                PrintUsage();
            }
        }
예제 #20
0
        /// <summary>
        /// Helper function to initialize the token cache for non-UWP apps. MSAL handles this automatically on UWP.
        /// </summary>
        /// <param name="provider">The instance of <see cref="MsalProvider"/> to init the cache for.</param>
        /// <param name="storageProperties">Properties for configuring the storage cache.</param>
        /// <param name="logger">Passing null uses the default TraceSource logger.</param>
        /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
        public static async Task InitTokenCacheAsync(
            this MsalProvider provider,
            StorageCreationProperties storageProperties,
            TraceSource logger = null)
        {
#if !WINDOWS_UWP
            // Token cache persistence (not required on UWP as MSAL does it for you)
            var cacheHelper = await MsalCacheHelper.CreateAsync(storageProperties, logger);

            cacheHelper.RegisterCache(provider.Client.UserTokenCache);
#endif
        }
예제 #21
0
        private async Task RegisterTokenCacheAsync(IPublicClientApplication app)
        {
            Context.Trace.WriteLine(
                "Configuring Microsoft Authentication token cache to instance shared with Microsoft developer tools...");

            if (!PlatformUtils.IsWindows() && !PlatformUtils.IsPosix())
            {
                string osType = PlatformUtils.GetPlatformInformation().OperatingSystemType;
                Context.Trace.WriteLine($"Token cache integration is not supported on {osType}.");
                return;
            }

            string clientId = app.AppConfig.ClientId;

            // We use the MSAL extension library to provide us consistent cache file access semantics (synchronisation, etc)
            // as other Microsoft developer tools such as the Azure PowerShell CLI.
            MsalCacheHelper helper = null;

            try
            {
                var storageProps = CreateTokenCacheProps(clientId, useLinuxFallback: false);
                helper = await MsalCacheHelper.CreateAsync(storageProps);

                // Test that cache access is working correctly
                helper.VerifyPersistence();
            }
            catch (MsalCachePersistenceException ex)
            {
                Context.Streams.Error.WriteLine("warning: cannot persist Microsoft Authentication data securely!");
                Context.Trace.WriteLine("Cannot persist Microsoft Authentication data securely!");
                Context.Trace.WriteException(ex);

                // On Linux the SecretService/keyring might not be available so we must fall-back to a plaintext file.
                if (PlatformUtils.IsLinux())
                {
                    Context.Trace.WriteLine("Using fall-back plaintext token cache on Linux.");
                    var storageProps = CreateTokenCacheProps(clientId, useLinuxFallback: true);
                    helper = await MsalCacheHelper.CreateAsync(storageProps);
                }
            }

            if (helper is null)
            {
                Context.Streams.Error.WriteLine("error: failed to set up Microsoft Authentication token cache!");
                Context.Trace.WriteLine("Failed to integrate with shared token cache!");
            }
            else
            {
                helper.RegisterCache(app.UserTokenCache);
                Context.Trace.WriteLine("Microsoft developer tools token cache configured.");
            }
        }
예제 #22
0
        private static async Task <MsalCacheHelper> CreateCacheHelperAsync()
        {
            StorageCreationProperties storageProperties;

            try
            {
                storageProperties = new StorageCreationPropertiesBuilder(
                    Config.CacheFileName,
                    Config.CacheDir,
                    Config.ClientId)
                                    .WithLinuxKeyring(
                    Config.LinuxKeyRingSchema,
                    Config.LinuxKeyRingCollection,
                    Config.LinuxKeyRingLabel,
                    Config.LinuxKeyRingAttr1,
                    Config.LinuxKeyRingAttr2)
                                    .WithMacKeyChain(
                    Config.KeyChainServiceName,
                    Config.KeyChainAccountName)
                                    .Build();

                var cacheHelper = await MsalCacheHelper.CreateAsync(
                    storageProperties).ConfigureAwait(false);

                cacheHelper.VerifyPersistence();
                return(cacheHelper);
            }
            catch (Exception e)
            {
                Console.WriteLine($"WARNING! Libsecret is not usable. " +
                                  $"Secrets will be stored in plaintext at {Path.Combine(Config.CacheDir, Config.CacheFileName)} !");
                Console.WriteLine($"Libsecret exception: " + e);

                storageProperties =
                    new StorageCreationPropertiesBuilder(
                        Config.CacheFileName,
                        Config.CacheDir,
                        Config.ClientId)
                    .WithLinuxUnprotectedFile()
                    .WithMacKeyChain(
                        Config.KeyChainServiceName,
                        Config.KeyChainAccountName)
                    .Build();

                var cacheHelper = await MsalCacheHelper.CreateAsync(storageProperties).ConfigureAwait(false);

                cacheHelper.VerifyPersistence();

                return(cacheHelper);
            }
        }
        private async Task InitializeAsync()
        {
            if (_attachSharedCache)
            {
                StorageCreationProperties storageProperties = new StorageCreationPropertiesBuilder(Constants.DefaultMsalTokenCacheName, Constants.DefaultMsalTokenCacheDirectory, _clientId)
                                                              .WithMacKeyChain(Constants.DefaultMsalTokenCacheKeychainService, Constants.DefaultMsalTokenCacheKeychainAccount)
                                                              .WithLinuxKeyring(Constants.DefaultMsalTokenCacheKeyringSchema, Constants.DefaultMsalTokenCacheKeyringCollection, Constants.DefaultMsalTokenCacheKeyringLabel, Constants.DefaultMsaltokenCacheKeyringAttribute1, Constants.DefaultMsaltokenCacheKeyringAttribute2)
                                                              .Build();

                MsalCacheHelper cacheHelper = await MsalCacheHelper.CreateAsync(storageProperties).ConfigureAwait(false);

                cacheHelper.RegisterCache(_client.UserTokenCache);
            }
        }
예제 #24
0
        /// <summary>
        /// Gets an aptly configured instance of the <see cref="MsalCacheStorage" /> class.
        /// </summary>
        /// <returns>An aptly configured instance of the <see cref="MsalCacheStorage" /> class.</returns>
        private MsalCacheHelper GetMsalCacheStorage()
        {
            StorageCreationPropertiesBuilder builder = new StorageCreationPropertiesBuilder(Path.GetFileName(CacheFilePath), Path.GetDirectoryName(CacheFilePath), ClientId);

            builder = builder.WithMacKeyChain(serviceName: "Microsoft.Developer.IdentityService", accountName: "MSALCache");
            builder = builder.WithLinuxKeyring(
                schemaName: "msal.cache",
                collection: "default",
                secretLabel: "MSALCache",
                attribute1: new KeyValuePair <string, string>("MsalClientID", "Microsoft.Developer.IdentityService"),
                attribute2: new KeyValuePair <string, string>("MsalClientVersion", "1.0.0.0"));

            return(MsalCacheHelper.CreateAsync(builder.Build(), new TraceSource("Partner Center PowerShell")).ConfigureAwait(false).GetAwaiter().GetResult());
        }
        private static async Task <MsalCacheHelper> CreateCacheHelperAsync()
        {
            StorageCreationProperties storageProperties;

            try
            {
                storageProperties = new StorageCreationPropertiesBuilder(
                    Config.CacheFileName,
                    Config.CacheDir)
                                    .WithLinuxKeyring(
                    Config.LinuxKeyRingSchema,
                    Config.LinuxKeyRingCollection,
                    Config.LinuxKeyRingLabel,
                    Config.LinuxKeyRingAttr1,
                    Config.LinuxKeyRingAttr2)
                                    .WithMacKeyChain(
                    Config.KeyChainServiceName,
                    Config.KeyChainAccountName)
                                    .WithCacheChangedEvent( // do NOT use unless really necessary, high perf penalty!
                    Config.ClientId,
                    Config.Authority)
                                    .Build();

                var cacheHelper = await MsalCacheHelper.CreateAsync(
                    storageProperties).ConfigureAwait(false);

                cacheHelper.VerifyPersistence();
                return(cacheHelper);
            }
            catch (MsalCachePersistenceException e)
            {
                Console.WriteLine($"WARNING! Unable to encrypt tokens at rest." +
                                  $" Saving tokens in plaintext at {Path.Combine(Config.CacheDir, Config.CacheFileName)} ! Please protect this directory or delete the file after use");
                Console.WriteLine($"Encryption exception: " + e);

                storageProperties =
                    new StorageCreationPropertiesBuilder(
                        Config.CacheFileName + ".plaintext", // do not use the same file name so as not to overwrite the encypted version
                        Config.CacheDir)
                    .WithUnprotectedFile()
                    .Build();

                var cacheHelper = await MsalCacheHelper.CreateAsync(storageProperties).ConfigureAwait(false);

                cacheHelper.VerifyPersistence();

                return(cacheHelper);
            }
        }
예제 #26
0
        private static async Task <MsalCacheHelper> GetProtectedCacheHelperAsync(bool async, CancellationToken cancellationToken)
        {
            using var asyncLock = await s_ProtectedCacheHelperLock.GetLockOrValueAsync(async, cancellationToken).ConfigureAwait(false);

            if (asyncLock.HasValue)
            {
                return(asyncLock.Value);
            }

            MsalCacheHelper cacheHelper = await GetProtectedCacheHelperAsync(async, Constants.DefaultMsalTokenCacheName).ConfigureAwait(false);

            asyncLock.SetValue(cacheHelper);

            return(cacheHelper);
        }
        private async Task InitializeCacheAsync()
        {
            // Building StorageCreationProperties
            var storageProperties =
                new StorageCreationPropertiesBuilder(
                    CacheFileName,
                    CacheDir,
                    ClientId)
                .Build();

            // This hooks up the cross-platform cache into MSAL
            var cacheHelper = await MsalCacheHelper.CreateAsync(storageProperties);

            cacheHelper.RegisterCache(app.UserTokenCache);
        }
예제 #28
0
        private static MsalCacheHelper InitializeCacheHelper(string clientId)
        {
            StorageCreationPropertiesBuilder builder = new StorageCreationPropertiesBuilder(Path.GetFileName(CacheFilePath), Path.GetDirectoryName(CacheFilePath), clientId);

            builder = builder.WithMacKeyChain(serviceName: "Microsoft.Developer.IdentityService", accountName: "MSALCache");
            builder = builder.WithLinuxKeyring(
                schemaName: "msal.cache",
                collection: "default",
                secretLabel: "MSALCache",
                attribute1: new KeyValuePair <string, string>("MsalClientID", "Microsoft.Developer.IdentityService"),
                attribute2: new KeyValuePair <string, string>("MsalClientVersion", "1.0.0.0"));

            StorageCreationProperties storageCreationProperties = builder.Build();

            return(MsalCacheHelper.CreateAsync(storageCreationProperties).ConfigureAwait(false).GetAwaiter().GetResult());
        }
예제 #29
0
        /// <summary>
        /// Notification that is triggered before token acquisition.
        /// </summary>
        /// <param name="args">Arguments related to the cache item impacted</param>
        public override void BeforeAccessNotification(TokenCacheNotificationArgs args)
        {
            MsalCacheHelper cacheStorage = GetMsalCacheHelper();

            args.AssertNotNull(nameof(args));

            try
            {
                args.TokenCache.DeserializeMsalV3(cacheStorage.LoadUnencryptedTokenCache());
            }
            catch (Exception)
            {
                cacheStorage.Clear();
                throw;
            }
        }
예제 #30
0
        private async Task <MsalCacheHelper> GetMsalCacheHelperAsync()
        {
            // There are options to set up the cache correctly using StorageCreationProperties on other OS's but that will need to be tested
            // for now only support windows
            if (helper == null && this.cacheEnabled && RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var fileName  = Path.GetFileName(cacheLocation);
                var directory = Path.GetDirectoryName(cacheLocation);

                var builder = new StorageCreationPropertiesBuilder(fileName, directory, this.clientId);
                StorageCreationProperties creationProps = builder.Build();
                helper = await MsalCacheHelper.CreateAsync(creationProps);
            }

            return(helper);
        }