public async Task SerializeDeserializeAsync() { var expRecord = new AuthenticationRecord(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), $"{Guid.NewGuid()}.{Guid.NewGuid()}", Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); byte[] buff = new byte[TestBufferSize]; var stream = new MemoryStream(buff); await expRecord.SerializeAsync(stream); IAccount expAccount = (AuthenticationAccount)expRecord; stream = new MemoryStream(buff, 0, (int)stream.Position); var actRecord = await AuthenticationRecord.DeserializeAsync(stream); IAccount actAccount = (AuthenticationAccount)actRecord; Assert.AreEqual(expRecord.Username, actRecord.Username); Assert.AreEqual(expRecord.Authority, actRecord.Authority); Assert.AreEqual(expRecord.HomeAccountId, actRecord.HomeAccountId); Assert.AreEqual(expRecord.TenantId, actRecord.TenantId); Assert.AreEqual(expRecord.ClientId, actRecord.ClientId); Assert.AreEqual(expAccount.Username, actAccount.Username); Assert.AreEqual(expAccount.Environment, actAccount.Environment); Assert.AreEqual(expAccount.HomeAccountId.Identifier, actAccount.HomeAccountId.Identifier); Assert.AreEqual(expAccount.HomeAccountId.ObjectId, actAccount.HomeAccountId.ObjectId); Assert.AreEqual(expAccount.HomeAccountId.TenantId, actAccount.HomeAccountId.TenantId); }
public static async Task Main() { InteractiveBrowserCredential credential; if (!File.Exists(AUTH_RECORD_PATH)) { credential = new InteractiveBrowserCredential(new InteractiveBrowserCredentialOptions { TokenCache = new PersistentTokenCache() }); AuthenticationRecord authRecord = await credential.AuthenticateAsync(); using var authRecordStream = new FileStream(AUTH_RECORD_PATH, FileMode.Create, FileAccess.Write); await authRecord.SerializeAsync(authRecordStream); await authRecordStream.FlushAsync(); } else { using var authRecordStream = new FileStream(AUTH_RECORD_PATH, FileMode.Open, FileAccess.Read); AuthenticationRecord authRecord = await AuthenticationRecord.DeserializeAsync(authRecordStream); credential = new InteractiveBrowserCredential(new InteractiveBrowserCredentialOptions { TokenCache = new PersistentTokenCache(), AuthenticationRecord = authRecord }); } var client = new SecretClient(new Uri("https://myvault.azure.vaults.net/"), credential); }
public void SerializeDeserializeInputChecks() { var record = new AuthenticationRecord(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); Assert.Throws <ArgumentNullException>(() => record.Serialize(null)); Assert.ThrowsAsync <ArgumentNullException>(async() => await record.SerializeAsync(null)); Assert.Throws <ArgumentNullException>(() => AuthenticationRecord.Deserialize(null)); Assert.ThrowsAsync <ArgumentNullException>(async() => await AuthenticationRecord.DeserializeAsync(null)); }
public void DeserializeCancellationTokenCancelled() { CancellationTokenSource cts = new CancellationTokenSource(); cts.Cancel(); var stream = new MemoryStream(TestBufferSize); Assert.CatchAsync <OperationCanceledException>(async() => await AuthenticationRecord.DeserializeAsync(stream, cts.Token)); }
private async Task <TokenCredential> GetCredentialAsyncImpl() { string authRecordPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "dotnet-eng", "auth-data.json" ); // Fetch the cached auth record, so that we don't have to browser auth every time the user uses the tool AuthenticationRecord record = null; if (File.Exists(authRecordPath)) { try { await using FileStream stream = File.Open(authRecordPath, FileMode.Open, FileAccess.Read, FileShare.Read); record = await AuthenticationRecord.DeserializeAsync(stream); } catch { // Failed to cache, next attempt will just re-prompt } } var cred = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCache = new PersistentTokenCache(false), AuthenticationRecord = record, } ); if (record == null) { // If we didn't already have a record, call authenticate async to trigger the browser login // so we can get the authentication record and store it record = await cred.AuthenticateAsync(); try { Directory.CreateDirectory(Path.GetDirectoryName(authRecordPath)); await using FileStream stream = File.Create(authRecordPath); await record.SerializeAsync(stream); } catch { // Failed to cache, next attempt will just re-prompt } } _userId = record.Username; return(cred); }
public static async Task Main() { #region Snippet:AuthenticationRecord_TokenCachePersistenceOptions const string TOKEN_CACHE_NAME = "MyTokenCache"; InteractiveBrowserCredential credential; AuthenticationRecord authRecord; // Check if an AuthenticationRecord exists on disk. // If it does not exist, get one and serialize it to disk. // If it does exist, load it from disk and deserialize it. if (!File.Exists(AUTH_RECORD_PATH)) { // Construct a credential with TokenCachePersistenceOptions specified to ensure that the token cache is persisted to disk. // We can also optionally specify a name for the cache to avoid having it cleared by other applications. credential = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions { Name = TOKEN_CACHE_NAME } }); // Call AuthenticateAsync to fetch a new AuthenticationRecord. authRecord = await credential.AuthenticateAsync(); // Serialize the AuthenticationRecord to disk so that it can be re-used across executions of this initialization code. using var authRecordStream = new FileStream(AUTH_RECORD_PATH, FileMode.Create, FileAccess.Write); await authRecord.SerializeAsync(authRecordStream); } else { // Load the previously serialized AuthenticationRecord from disk and deserialize it. using var authRecordStream = new FileStream(AUTH_RECORD_PATH, FileMode.Open, FileAccess.Read); authRecord = await AuthenticationRecord.DeserializeAsync(authRecordStream); // Construct a new client with our TokenCachePersistenceOptions with the addition of the AuthenticationRecord property. // This tells the credential to use the same token cache in addition to which account to try and fetch from cache when GetToken is called. credential = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions { Name = TOKEN_CACHE_NAME }, AuthenticationRecord = authRecord }); } // Construct our client with the credential which is connected to the token cache // with the capability of silent authentication for the account specified in the AuthenticationRecord. var client = new SecretClient(new Uri("https://myvault.vault.azure.net/"), credential); #endregion }
public static async Task <TokenCredential> GetUserCredentialAsync() { if (!File.Exists(AUTH_RECORD_PATH)) { #region Snippet:Identity_ClientSideUserAuthentication_Persist_TokenCache var credential = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions() }); #endregion #region Snippet:Identity_ClientSideUserAuthentication_Persist_AuthRecord AuthenticationRecord authRecord = await credential.AuthenticateAsync(); using (var authRecordStream = new FileStream(AUTH_RECORD_PATH, FileMode.Create, FileAccess.Write)) { await authRecord.SerializeAsync(authRecordStream); } #endregion return(credential); } else { #region Snippet:Identity_ClientSideUserAuthentication_Persist_SilentAuth AuthenticationRecord authRecord; using (var authRecordStream = new FileStream(AUTH_RECORD_PATH, FileMode.Open, FileAccess.Read)) { authRecord = await AuthenticationRecord.DeserializeAsync(authRecordStream); } var credential = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions(), AuthenticationRecord = authRecord }); #endregion return(credential); } }
public async Task SerializeDeserializeAsync() { var expRecord = new AuthenticationRecord(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); byte[] buff = new byte[TestBufferSize]; var stream = new MemoryStream(buff); await expRecord.SerializeAsync(stream); stream = new MemoryStream(buff, 0, (int)stream.Position); var actRecord = await AuthenticationRecord.DeserializeAsync(stream); Assert.AreEqual(expRecord.Username, actRecord.Username); Assert.AreEqual(expRecord.Authority, actRecord.Authority); Assert.AreEqual(expRecord.HomeAccountId, actRecord.HomeAccountId); Assert.AreEqual(expRecord.TenantId, actRecord.TenantId); }
static async Task Main(string[] args) { // var cred = new DefaultAzureCredential(); // var token = cred.GetTokenAsync( // new TokenRequestContext(scopes: new string[] { "your scope here" }) { } // ); // 1. Create TokenCredential object with TokenCachePersistenceOptions set var credentialOne = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions() { Name = "AuthenticationRecord.cache" } }); // 2. Prompt user to authenticate AuthenticationRecord authRecordWrite = await credentialOne.AuthenticateAsync(); // 3. Save AuthenticationRecord to disk using (var authRecordStreamWrite = new FileStream("AuthRecord.json", FileMode.Create, FileAccess.Write)) { await authRecordWrite.SerializeAsync(authRecordStreamWrite); } // A future user session where we want to silent auth with TokenCache and AuthenticationRecord // 4. Read the AuthenticationRecord from disk AuthenticationRecord authRecordRead; using (var authRecordStreamRead = new FileStream("AuthRecord.json", FileMode.Open, FileAccess.Read)) { authRecordRead = await AuthenticationRecord.DeserializeAsync(authRecordStreamRead); } // 5. Create TokenCredential object with TokenCache and use persisted AuthenticationRecord var credentialTwo = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions() { Name = "AuthenticationRecord.cache" }, AuthenticationRecord = authRecordRead }); // 5.1 Same as above but with DisableAutomaticAuthentication set to true // var credentialTwo = new InteractiveBrowserCredential( // new InteractiveBrowserCredentialOptions // { // TokenCachePersistenceOptions = new TokenCachePersistenceOptions() // { // Name = "AuthenticationRecord.cache" // }, // AuthenticationRecord = authRecordRead, // DisableAutomaticAuthentication = true // }); // 6. Use the new TokenCredential object. User will not be prompted to re-authenticate if token has expired. var client = new SecretClient(new Uri("https://memealyzerdevkv.vault.azure.net/"), credentialTwo); try { var secret = await client.GetSecretAsync("CosmosKey"); Console.WriteLine(secret.Value.Value); } catch (AuthenticationRequiredException ex) { Console.WriteLine("You set InteractiveBrowserCredentialOptions.DisableAutomaticAuthentication to true and the user token has expired or has been revoked."); Console.WriteLine(ex.ToString()); } }