示例#1
0
        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 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);
        }
示例#3
0
        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));
        }
        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);
        }
示例#5
0
        public void SerializeCancellationTokenCancelled()
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            cts.Cancel();

            var expRecord = new AuthenticationRecord(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());

            var stream = new MemoryStream(TestBufferSize);

            Assert.CatchAsync <OperationCanceledException>(async() => await expRecord.SerializeAsync(stream, cts.Token));
        }
示例#6
0
        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);
        }
示例#8
0
        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());
            }
        }