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. }
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(); }
/// <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 }
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"); 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")); s_storageCreationProperties = builder.Build(); }
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); }
/// <summary> /// Initializes a new instance of the <see cref="AdalCacheStorage"/> class. /// </summary> /// <param name="creationProperties">Creation properties for storage on disk</param> /// <param name="logger">logger</param> public AdalCacheStorage(StorageCreationProperties creationProperties, TraceSource logger) { _logger = logger ?? s_staticLogger.Value; CreationProperties = creationProperties ?? throw new ArgumentNullException(nameof(creationProperties)); logger.TraceEvent(TraceEventType.Information, /*id*/ 0, $"Initializing '{nameof(AdalCacheStorage)}' with cacheFilePath '{creationProperties.CacheDirectory}'"); try { logger.TraceEvent(TraceEventType.Information, /*id*/ 0, $"Getting last write file time for a missing file in localappdata"); _fileNotFoundOffset = File.GetLastWriteTimeUtc(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), $"{Guid.NewGuid().FormatGuidAsString()}.dll")); } catch (Exception e) { logger.TraceEvent(TraceEventType.Information, /*id*/ 0, $"Problem getting last file write time for missing file, trying temp path('{Path.GetTempPath()}'). {e.Message}"); _fileNotFoundOffset = File.GetLastWriteTimeUtc(Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid().FormatGuidAsString()}.dll")); } CacheFilePath = Path.Combine(creationProperties.CacheDirectory, creationProperties.CacheFileName); _lastWriteTime = _fileNotFoundOffset; logger.TraceEvent(TraceEventType.Information, /*id*/ 0, $"Finished initializing '{nameof(AdalCacheStorage)}'"); }
/// <summary> /// Initializes a new instance of the <see cref="AdalCacheStorage"/> class. /// </summary> /// <param name="creationProperties">Creation properties for storage on disk</param> /// <param name="logger">logger</param> public AdalCacheStorage(StorageCreationProperties creationProperties, TraceSource logger) { _logger = logger ?? s_staticLogger.Value; CreationProperties = creationProperties ?? throw new ArgumentNullException(nameof(creationProperties)); logger.TraceEvent(TraceEventType.Information, /*id*/ 0, $"Initialized '{nameof(AdalCacheStorage)}' with cacheFilePath '{creationProperties.CacheDirectory}'"); }
private async Task <MsalCacheHelperWrapper> InitializeCacheHelper(bool async, StorageCreationProperties storageProperties) { if (async) { await _cacheHelperWrapper.InitializeAsync(storageProperties).ConfigureAwait(false); } else { #pragma warning disable AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead. _cacheHelperWrapper.InitializeAsync(storageProperties).GetAwaiter().GetResult(); #pragma warning restore AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead. } return(_cacheHelperWrapper); }
/// <summary> /// Creates a new instance of Microsoft.Identity.Client.Extensions.Msal.MsalCacheHelper. /// To configure MSAL to use this cache persistence, call Microsoft.Identity.Client.Extensions.Msal.MsalCacheHelper.RegisterCache(Microsoft.Identity.Client.ITokenCache) /// </summary> /// <param name="storageCreationProperties"></param> /// <param name="logger">Passing null uses a default logger</param> /// <returns>A new instance of Microsoft.Identity.Client.Extensions.Msal.MsalCacheHelper.</returns> public virtual async Task InitializeAsync(StorageCreationProperties storageCreationProperties, TraceSource logger = null) { _helper = await MsalCacheHelper.CreateAsync(storageCreationProperties, logger).ConfigureAwait(false); }
protected override async Task <bool> RunInternalAsync(StringBuilder log, IList <string> additionalFiles) { if (MicrosoftAuthentication.CanUseBroker(_context)) { log.Append("Checking broker initialization state..."); if (MicrosoftAuthentication.IsBrokerInitialized) { log.AppendLine(" Initialized"); } else { log.AppendLine(" Not initialized"); log.Append("Initializing broker..."); MicrosoftAuthentication.InitializeBroker(); log.AppendLine("OK"); } } else { log.AppendLine("Broker not supported."); } var msAuth = new MicrosoftAuthentication(_context); log.AppendLine($"Flow type is: {msAuth.GetFlowType()}"); log.Append("Gathering MSAL token cache data..."); StorageCreationProperties cacheProps = msAuth.CreateTokenCacheProps(true); log.AppendLine(" OK"); log.AppendLine($"CacheDirectory: {cacheProps.CacheDirectory}"); log.AppendLine($"CacheFileName: {cacheProps.CacheFileName}"); log.AppendLine($"CacheFilePath: {cacheProps.CacheFilePath}"); if (PlatformUtils.IsMacOS()) { log.AppendLine($"MacKeyChainAccountName: {cacheProps.MacKeyChainAccountName}"); log.AppendLine($"MacKeyChainServiceName: {cacheProps.MacKeyChainServiceName}"); } else if (PlatformUtils.IsLinux()) { log.AppendLine($"KeyringCollection: {cacheProps.KeyringCollection}"); log.AppendLine($"KeyringSchemaName: {cacheProps.KeyringSchemaName}"); log.AppendLine($"KeyringSecretLabel: {cacheProps.KeyringSecretLabel}"); log.AppendLine($"KeyringAttribute1: ({cacheProps.KeyringAttribute1.Key},{cacheProps.KeyringAttribute1.Value})"); log.AppendLine($"KeyringAttribute2: ({cacheProps.KeyringAttribute2.Key},{cacheProps.KeyringAttribute2.Value})"); } log.Append("Creating cache helper..."); var cacheHelper = await MsalCacheHelper.CreateAsync(cacheProps); log.AppendLine(" OK"); try { log.Append("Verifying MSAL token cache persistence..."); cacheHelper.VerifyPersistence(); log.AppendLine(" OK"); } catch (Exception) { log.AppendLine(" Failed"); throw; } return(true); }
/// <summary> /// Initializes a new instance of the <see cref="AdalCacheStorage"/> class. /// </summary> /// <param name="creationProperties">Creation properties for storage on disk</param> /// <param name="logger">logger</param> public AdalCacheStorage(StorageCreationProperties creationProperties, TraceSource logger) { _logger = logger == null ? s_staticLogger.Value : new TraceSourceLogger(logger); CreationProperties = creationProperties ?? throw new ArgumentNullException(nameof(creationProperties)); _logger.LogInformation($"Initialized '{nameof(AdalCacheStorage)}' with cacheFilePath '{creationProperties.CacheDirectory}'"); }
/// <summary> /// Register a Msal persistent cache to handle tokens save and restore /// </summary> /// <param name="storageCreationProperties">Configured storage</param> /// <returns></returns> public async Task RegisterTokenStorageAsync(StorageCreationProperties storageCreationProperties) { var cacheHelper = await MsalCacheHelper.CreateAsync(storageCreationProperties).ConfigureAwait(false); cacheHelper.RegisterCache(publicClientApplication.UserTokenCache); }