コード例 #1
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.ConfigureAppConfiguration((context, config) =>
            {
                var configuration = config.Build();

                // Get data from secrets
                var connectionString = configuration.GetConnectionString("AppConfiguration");

#if DEBUG
                var keyVaultCredential = new AzureCliCredential();
#else
                var keyVaultCredential = new DefaultAzureCredential();
#endif

                config.AddAzureAppConfiguration(options =>
                {
                    // We can connect to Azure AppConfiguration using a connection string or an uri with credentials
                    options.Connect(connectionString)
                    .Select(KeyFilter.Any, LabelFilter.Null)
                    // We can connect to Azure Key Vault using credentials
                    .ConfigureKeyVault(kv =>
                    {
                        kv.SetCredential(keyVaultCredential);
                    });
                });
            }).UseStartup <Startup>();
        });
コード例 #2
0
        public async Task AuthenticateWithCliCredential(
            [Values(null, TenantIdHint)] string tenantId,
            [Values(true)] bool allowMultiTenantAuthentication,
            [Values(null, TenantId)] string explicitTenantId)
        {
            var context = new TokenRequestContext(new[] { Scope }, tenantId: tenantId);
            var options = new AzureCliCredentialOptions {
                TenantId = explicitTenantId, AllowMultiTenantAuthentication = allowMultiTenantAuthentication
            };
            string expectedTenantId = TenantIdResolver.Resolve(explicitTenantId, context, options.AllowMultiTenantAuthentication);

            var(expectedToken, expectedExpiresOn, processOutput) = CredentialTestHelpers.CreateTokenForAzureCli();

            var testProcess = new TestProcess {
                Output = processOutput
            };
            AzureCliCredential credential =
                InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess, true), options));
            AccessToken actualToken = await credential.GetTokenAsync(context);

            Assert.AreEqual(expectedToken, actualToken.Token);
            Assert.AreEqual(expectedExpiresOn, actualToken.ExpiresOn);

            var expectTenantId = expectedTenantId != null;

            if (expectTenantId)
            {
                Assert.That(testProcess.StartInfo.Arguments, Does.Contain($"-tenant {expectedTenantId}"));
            }
            else
            {
                Assert.That(testProcess.StartInfo.Arguments, Does.Not.Contain("-tenant"));
            }
        }
コード例 #3
0
        public void AuthenticateWithCliCredential_InvalidJsonOutput([Values("", "{}", "{\"Some\": false}", "{\"accessToken\": \"token\"}", "{\"expiresOn\" : \"1900-01-01 00:00:00.123456\"}")] string jsonContent)
        {
            var testProcess = new TestProcess {
                Output = jsonContent
            };
            AzureCliCredential credential = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));

            Assert.CatchAsync <AuthenticationFailedException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));
        }
コード例 #4
0
        public void CliCredentialAuthenticationFailedException()
        {
            string mockResult = $"mock-result";

            var mockCliCredentialClient = new MockAzureCliCredentialClient((mockResult, 1));

            AzureCliCredential credential = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), mockCliCredentialClient));

            var ex = Assert.ThrowsAsync <AuthenticationFailedException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));
        }
コード例 #5
0
        public void AuthenticateWithCliCredential_ExceptionScenarios(string errorMessage, string expectedMessage, Type exceptionType)
        {
            var testProcess = new TestProcess {
                Error = errorMessage
            };
            AzureCliCredential credential = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));
            var ex = Assert.ThrowsAsync(exceptionType, async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));

            Assert.AreEqual(expectedMessage, ex.Message);
        }
コード例 #6
0
        public void AuthenticateWithCliCredential_AzureCliUnknownError()
        {
            string mockResult  = "mock-result";
            var    testProcess = new TestProcess {
                Error = mockResult
            };
            AzureCliCredential credential = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));

            Assert.ThrowsAsync <AuthenticationFailedException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));
        }
コード例 #7
0
        public void AuthenticateWithCliCredential_AzureCliNotInstalled([Values("'az' is not recognized", "az: command not found", "az: not found")] string errorMessage)
        {
            string expectedMessage = "Azure CLI not installed";
            var    testProcess     = new TestProcess {
                Error = errorMessage
            };
            AzureCliCredential credential = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));
            var ex = Assert.ThrowsAsync <CredentialUnavailableException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));

            Assert.AreEqual(expectedMessage, ex.Message);
        }
コード例 #8
0
        public void AuthenticateWithCliCredential_AzNotLogIn()
        {
            string expectedExMessage = $"Please run 'az login' to set up account";
            var    testProcess       = new TestProcess {
                Error = "Please run 'az login'"
            };
            AzureCliCredential credential = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));
            var ex = Assert.ThrowsAsync <CredentialUnavailableException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));

            Assert.AreEqual(expectedExMessage, ex.Message);
        }
コード例 #9
0
        public async Task AuthenticateWithCliCredential()
        {
            var expectedToken = "mock-cli-access-token";
            var testProcess   = new TestProcess {
                Output = $"{{ \"accessToken\": \"{expectedToken}\", \"expiresOn\": \"1900-01-01 00:00:00.123456\" }}"
            };
            AzureCliCredential credential  = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));
            AccessToken        actualToken = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default));

            Assert.AreEqual(expectedToken, actualToken.Token);
        }
コード例 #10
0
        public void AuthenticateWithCliCredential_CanceledByUser()
        {
            var cts         = new CancellationTokenSource();
            var testProcess = new TestProcess {
                Timeout = 10000
            };

            testProcess.Started += (o, e) => cts.Cancel();
            AzureCliCredential credential = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));

            Assert.CatchAsync <OperationCanceledException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default), cts.Token));
        }
コード例 #11
0
        public void CliCredentialAzNotLogInException()
        {
            string expectedExMessage = $"Please run 'az login' to set up account";

            var mockCliCredentialClient = new MockAzureCliCredentialClient(("Please run 'az login'", 1));

            AzureCliCredential credential = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), mockCliCredentialClient));

            var ex = Assert.ThrowsAsync <CredentialUnavailableException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));

            Assert.AreEqual(expectedExMessage, ex.Message);
        }
コード例 #12
0
        public async Task AuthenticateWithCliCredential_ExpiresIn()
        {
            var(expectedToken, expectedExpiresOn, processOutput) = CredentialTestHelpers.CreateTokenForAzureCliExpiresIn(1800);

            var testProcess = new TestProcess {
                Output = processOutput
            };
            AzureCliCredential credential  = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));
            AccessToken        actualToken = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default));

            Assert.AreEqual(expectedToken, actualToken.Token);
            Assert.LessOrEqual(expectedExpiresOn, actualToken.ExpiresOn);
        }
コード例 #13
0
        public async Task AuthenticateWithCliCredential_ExpiresIn()
        {
            var expectedToken = "mock-cli-access-token";
            var expectedTime  = DateTimeOffset.Now.AddMinutes(30);
            var testProcess   = new TestProcess {
                Output = $"{{ \"accessToken\": \"{expectedToken}\", \"expiresIn\": 1800 }}"
            };
            AzureCliCredential credential  = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));
            AccessToken        actualToken = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default));

            Assert.AreEqual(expectedToken, actualToken.Token);
            Assert.LessOrEqual(expectedTime, actualToken.ExpiresOn);
        }
コード例 #14
0
        public async Task GetTokenMockAsync()
        {
            var expectedToken = "mock-cli-access-token";

            string mockResult = $"{{ \"accessToken\": \"{expectedToken}\", \"expiresOn\": \"1900-01-01 00:00:00.123456\" }}";

            var mockCliCredentialClient = new MockAzureCliCredentialClient((mockResult, 0));

            AzureCliCredential credential = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), mockCliCredentialClient));

            AccessToken actualToken = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default));

            Assert.AreEqual(expectedToken, actualToken.Token);
        }
コード例 #15
0
        public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
        {
            var config      = builder.ConfigurationBuilder;
            var curSettings = config.Build();

#if DEBUG
            var creds = new AzureCliCredential();
#else
            var creds = new DefaultAzureCredential();
#endif

            config.AddAzureKeyVault(new Uri(curSettings["KeyVaultUrl"]), creds);
            config.AddAzureAppConfiguration(curSettings["AppConfigConnectionString"]);
        }
コード例 #16
0
        static async Task Main(string[] args)
        {
            try
            {
                var cred   = new AzureCliCredential();
                var client = new KeyClient(new Uri("https://jongkv.vault.azure.net"), cred);
                var key    = await client.GetKeyAsync("key1");

                Console.WriteLine(key.Value.Name);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            while (true)
            {
            }
        }
コード例 #17
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            // Load configuration from Azure App Configuration
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            var configuration = configurationBuilder
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                                .AddEnvironmentVariables()
                                .AddUserSecrets(Assembly.GetExecutingAssembly())
                                .Build();

            // Get data from secrets
            var connectionString = configuration.GetConnectionString("AppConfiguration");

#if DEBUG
            var keyVaultCredential = new AzureCliCredential();
#else
            var keyVaultCredential = new DefaultAzureCredential();
#endif
            // Create a new configurationbuilder and add appconfiguration
            configuration = configurationBuilder.AddAzureAppConfiguration(options =>
            {
                options.Connect(connectionString)
                .Select(KeyFilter.Any, LabelFilter.Null)
                // We can connect to Azure Key Vault using credentials
                .ConfigureKeyVault(kv =>
                {
                    kv.SetCredential(keyVaultCredential);
                });
            }).Build();

            builder.Services.AddSingleton <IConfiguration>(configuration);
            builder.Services.AddSingleton <IKeyVaultService>(s => new KeyVaultService(configuration["AppSettings:KeyVault:Name"]));
            builder.Services.Configure <BlobStorageRepositoryOptions>(configuration.GetSection("BlobStorageRepositoryOptions"));
            builder.Services.AddSingleton <IBlobStorageRepository, BlobStorageRepository>();
            builder.Services.Configure <FormRecognizerServiceOptions>(configuration.GetSection("FormRecognizerServiceOptions"));
            builder.Services.AddSingleton <IFormRecognizerService, FormRecognizerService>();
            builder.Services.AddSingleton <XadesService>();
        }
コード例 #18
0
        public void CliCredentialAzureCLINotInstalledException()
        {
            string expectedMessage = $"Azure CLI not installed";

            var mockCliCreClientList = new List <MockAzureCliCredentialClient>();

            // Mock client for Windows Azure CLI not installed error message
            mockCliCreClientList.Add(new MockAzureCliCredentialClient(("'az' is not recognized", 1)));

            // Mock client for Linux Azure CLI not installed error message
            mockCliCreClientList.Add(new MockAzureCliCredentialClient(("az: command not found", 1)));

            // Mock client for MacOS Azure CLI not installed error message
            mockCliCreClientList.Add(new MockAzureCliCredentialClient(("az: not found", 1)));

            foreach (var mockCliCredentialClient in mockCliCreClientList)
            {
                AzureCliCredential credential = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), mockCliCredentialClient));

                var ex = Assert.ThrowsAsync <CredentialUnavailableException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));

                Assert.AreEqual(expectedMessage, ex.Message);
            }
        }