/// <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); }
private async Task InitializeGlobalProviderAsync() { if (ProviderManager.Instance.GlobalProvider == null) { var provider = new MsalProvider(ClientId, Scopes, null, false, true); // Configure the token cache storage for non-UWP applications. var storageProperties = new StorageCreationPropertiesBuilder(CacheConfig.CacheFileName, CacheConfig.CacheDir) .WithLinuxKeyring( CacheConfig.LinuxKeyRingSchema, CacheConfig.LinuxKeyRingCollection, CacheConfig.LinuxKeyRingLabel, CacheConfig.LinuxKeyRingAttr1, CacheConfig.LinuxKeyRingAttr2) .WithMacKeyChain( CacheConfig.KeyChainServiceName, CacheConfig.KeyChainAccountName) .Build(); await provider.InitTokenCacheAsync(storageProperties); ProviderManager.Instance.GlobalProvider = provider; await provider.TrySilentSignInAsync(); } }
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); } }
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 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); } }
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}."); } }
public void UnprotectedOptionMutuallyExclusiveWithOtherOptions() { var builder = new StorageCreationPropertiesBuilder( Path.GetFileName(CacheFilePath), Path.GetDirectoryName(CacheFilePath)); builder = builder.WithMacKeyChain(serviceName: "Microsoft.Developer.IdentityService", accountName: "MSALCache"); builder.WithUnprotectedFile(); AssertException.Throws <ArgumentException>(() => builder.Build()); builder = new StorageCreationPropertiesBuilder( Path.GetFileName(CacheFilePath), Path.GetDirectoryName(CacheFilePath)); 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")); builder.WithUnprotectedFile(); AssertException.Throws <ArgumentException>(() => builder.Build()); builder = new StorageCreationPropertiesBuilder( Path.GetFileName(CacheFilePath), Path.GetDirectoryName(CacheFilePath)); builder.WithLinuxUnprotectedFile(); builder.WithUnprotectedFile(); AssertException.Throws <ArgumentException>(() => builder.Build()); }
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(); }
public void CacheStorageFactory_WithFallback_Linux() { var storageWithKeyRing = new StorageCreationPropertiesBuilder( Path.GetFileName(CacheFilePath), Path.GetDirectoryName(CacheFilePath), "ClientIDGoesHere") .WithMacKeyChain(serviceName: "Microsoft.Developer.IdentityService", accountName: "MSALCache") .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")) .Build(); // Tests run on machines without Libsecret MsalCacheStorage store = MsalCacheStorage.Create(storageWithKeyRing, logger: _logger); Assert.IsTrue(store.CacheAccessor is LinuxKeyringAccessor); // ADO Linux test agents do not have libsecret installed by default // If you run this test on a Linux box with UI / LibSecret, then this test will fail // because the statement below will not throw. AssertException.Throws <MsalCachePersistenceException>( () => store.VerifyPersistence()); store = MsalCacheStorage.Create(s_storageCreationProperties, _logger); Assert.IsTrue(store.CacheAccessor is FileAccessor); store.VerifyPersistence(); }
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))); }
public void CacheFallback() { const string data = "data"; string cacheFilePathFallback = CacheFilePath + "fallback"; var plaintextStorage = new StorageCreationPropertiesBuilder( Path.GetFileName(cacheFilePathFallback), Path.GetDirectoryName(CacheFilePath)) .WithUnprotectedFile() .Build(); Storage unprotectedStore = Storage.Create(plaintextStorage, _logger); Assert.IsTrue(unprotectedStore.CacheAccessor is FileAccessor); unprotectedStore.VerifyPersistence(); unprotectedStore.WriteData(Encoding.UTF8.GetBytes(data)); // Unprotected cache file should exist Assert.IsTrue(File.Exists(plaintextStorage.CacheFilePath)); string dataReadFromPlaintext = File.ReadAllText(plaintextStorage.CacheFilePath); Assert.AreEqual(data, dataReadFromPlaintext); // Verify that file permissions are set to 600 FileHelper.AssertChmod600(plaintextStorage.CacheFilePath); }
public void TestInitialize() { _storageCreationPropertiesBuilder = new StorageCreationPropertiesBuilder( Path.GetFileName(CacheFilePath), Path.GetDirectoryName(CacheFilePath), "1d18b3b0-251b-4714-a02a-9956cec86c2d"); _storageCreationPropertiesBuilder = _storageCreationPropertiesBuilder.WithMacKeyChain(serviceName: "Microsoft.Developer.IdentityService", accountName: "MSALCache"); _storageCreationPropertiesBuilder.WithLinuxUnprotectedFile(); }
public void TestInitialize() { _cacheFilePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()); _storageCreationPropertiesBuilder = new StorageCreationPropertiesBuilder( Path.GetFileName(_cacheFilePath), Path.GetDirectoryName(_cacheFilePath)); _storageCreationPropertiesBuilder = _storageCreationPropertiesBuilder.WithMacKeyChain(serviceName: "Microsoft.Developer.IdentityService", accountName: "MSALCache"); _storageCreationPropertiesBuilder.WithLinuxUnprotectedFile(); }
public static void ClassInitialize(TestContext _) { var builder = new StorageCreationPropertiesBuilder(Path.GetFileName(CacheFilePath), Path.GetDirectoryName(CacheFilePath), "ClientIDGoesHere"); builder = builder.WithMacKeyChain(serviceName: "Microsoft.Developer.IdentityService", accountName: "MSALCache"); // Tests run on machines without Libsecret builder = builder.WithLinuxUnprotectedFile(); s_storageCreationProperties = builder.Build(); }
public void TestInitialize() { _storageCreationPropertiesBuilder = new StorageCreationPropertiesBuilder(Path.GetFileName(CacheFilePath), Path.GetDirectoryName(CacheFilePath), "ClientIDGoesHere"); _storageCreationPropertiesBuilder = _storageCreationPropertiesBuilder.WithMacKeyChain(serviceName: "Microsoft.Developer.IdentityService", accountName: "MSALCache"); _storageCreationPropertiesBuilder = _storageCreationPropertiesBuilder.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")); }
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); }
private async Task <MsalCacheHelperWrapper> GetFallbackCacheHelperAsync(bool async, string name = Constants.DefaultMsalTokenCacheName) { StorageCreationProperties storageProperties = new StorageCreationPropertiesBuilder(name, Constants.DefaultMsalTokenCacheDirectory) .WithMacKeyChain(Constants.DefaultMsalTokenCacheKeychainService, name) .WithLinuxUnprotectedFile() .Build(); MsalCacheHelperWrapper cacheHelper = await InitializeCacheHelper(async, storageProperties).ConfigureAwait(false); return(cacheHelper); }
private async Task <MsalCacheHelperWrapper> GetProtectedCacheHelperAsync(bool async, string name) { StorageCreationProperties storageProperties = new StorageCreationPropertiesBuilder(name, Constants.DefaultMsalTokenCacheDirectory) .WithMacKeyChain(Constants.DefaultMsalTokenCacheKeychainService, name) .WithLinuxKeyring(Constants.DefaultMsalTokenCacheKeyringSchema, Constants.DefaultMsalTokenCacheKeyringCollection, name, Constants.DefaultMsaltokenCacheKeyringAttribute1, Constants.DefaultMsaltokenCacheKeyringAttribute2) .Build(); MsalCacheHelperWrapper cacheHelper = await InitializeCacheHelper(async, storageProperties).ConfigureAwait(false); return(cacheHelper); }
/// <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))); }
public static void ClassInitialize(TestContext _) { var builder = new StorageCreationPropertiesBuilder(Path.GetFileName(CacheFilePath), Path.GetDirectoryName(CacheFilePath)); builder = builder.WithMacKeyChain(serviceName: "Microsoft.Developer.IdentityService", accountName: "MSALCache"); builder = builder.WithLinuxKeyring( schemaName: "adal.cache", collection: "default", secretLabel: "ADALCache", attribute1: new KeyValuePair <string, string>("ADALClientID", "Microsoft.Developer.IdentityService"), attribute2: new KeyValuePair <string, string>("AdalClientVersion", "1.0.0.0")); s_storageCreationProperties = builder.Build(); }
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); } }
protected async ValueTask <TClient> GetClientAsync(bool async, CancellationToken cancellationToken) { using var asyncLock = await _clientAsyncLock.GetLockOrValueAsync(async, cancellationToken).ConfigureAwait(false); if (asyncLock.HasValue) { return(asyncLock.Value); } var client = await CreateClientAsync(async, cancellationToken).ConfigureAwait(false); if (EnablePersistentCache) { MsalCacheHelper cacheHelper; StorageCreationProperties storageProperties = new StorageCreationPropertiesBuilder(Constants.DefaultMsalTokenCacheName, Constants.DefaultMsalTokenCacheDirectory, s_msalCacheClientId) .WithMacKeyChain(Constants.DefaultMsalTokenCacheKeychainService, Constants.DefaultMsalTokenCacheKeychainAccount) .WithLinuxKeyring(Constants.DefaultMsalTokenCacheKeyringSchema, Constants.DefaultMsalTokenCacheKeyringCollection, Constants.DefaultMsalTokenCacheKeyringLabel, Constants.DefaultMsaltokenCacheKeyringAttribute1, Constants.DefaultMsaltokenCacheKeyringAttribute2) .Build(); try { cacheHelper = await CreateCacheHelper(storageProperties, async).ConfigureAwait(false); cacheHelper.VerifyPersistence(); } catch (MsalCachePersistenceException) { if (AllowUnencryptedCache) { storageProperties = new StorageCreationPropertiesBuilder(Constants.DefaultMsalTokenCacheName, Constants.DefaultMsalTokenCacheDirectory, s_msalCacheClientId) .WithMacKeyChain(Constants.DefaultMsalTokenCacheKeychainService, Constants.DefaultMsalTokenCacheKeychainAccount) .WithLinuxUnprotectedFile() .Build(); cacheHelper = await CreateCacheHelper(storageProperties, async).ConfigureAwait(false); cacheHelper.VerifyPersistence(); } else { throw; } } cacheHelper.RegisterCache(client.UserTokenCache); } asyncLock.SetValue(client); return(client); }
/// <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()); }
/// <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 MsalCacheStorage 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(new MsalCacheStorage(builder.Build())); }
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); } }
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); } }
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); }
public void TestInitialize() { var tmpFilePath = Path.GetTempFileName(); _builder = new StorageCreationPropertiesBuilder( Path.GetFileName(tmpFilePath), Path.GetDirectoryName(tmpFilePath), "1234") .WithMacKeyChain(serviceName: "testFoo", accountName: "accountName") .WithLinuxKeyring( schemaName: "msal.cache", collection: "default", secretLabel: "MSALCache", attribute1: new KeyValuePair <string, string>("MsalClientID", "testFoo"), attribute2: new KeyValuePair <string, string>("MsalClientVersion", "1.0.0.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()); }
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); }