Example #1
0
        static void Main(string[] args)
        {
            var storageUri    = Environment.GetEnvironmentVariable("APP_STORAGE_URI");
            var containerName = Environment.GetEnvironmentVariable("APP_STORAGE_CONTAINER");
            var serviceScope  = Environment.GetEnvironmentVariable("APP_SERVICE_SCOPE");
            var serviceUri    = Environment.GetEnvironmentVariable("APP_SERVICE_URI");

            var credential = new ChainedTokenCredential(
                new ManagedIdentityCredential(),
                new EnvironmentCredential());

            var functionToken = credential.GetToken(new TokenRequestContext(new string[] { serviceScope }));

            var blobServiceClient = new BlobServiceClient(
                new Uri(storageUri),
                credential);

            var blobContainerClient = blobServiceClient.GetBlobContainerClient(containerName);
            var blobClient          = blobContainerClient.GetBlobClient($"{DateTime.Now.ToString("yyyy-MM-ddTHH-mm-ss")}.jpg");

            blobClient.Upload("test.jpg");

            var functionClient = new HttpClient();

            functionClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                "Bearer",
                functionToken.Token);

            var response = functionClient.GetAsync(serviceUri).Result;

            response.EnsureSuccessStatusCode();
        }
Example #2
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["deviceid"];


            string primaryKey = "";
            var    credential = new ChainedTokenCredential(
                new ManagedIdentityCredential(),
                new VisualStudioCodeCredential());
            var client = new SecretClient(new Uri("https://deviceonboardingkeyvault.vault.azure.net/"), credential);
            var secret = client.GetSecret("dpsconnectionstring");

            using (var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(secret.Value.Value)){
                var attestation = new SymmetricKeyAttestation("", "");
                var ie          = new IndividualEnrollment(name, attestation);
                var enrollment  = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(ie);

                var keys = enrollment.Attestation as SymmetricKeyAttestation;
                primaryKey = keys.PrimaryKey;
                log.LogInformation(enrollment.IotHubHostName);
            }

            return(new OkObjectResult(primaryKey));
        }
        protected SecretClient GetSecretClient()
        {
            var credentials = new ChainedTokenCredential(new[] { new AzureServiceTokenProviderCredential(TokenCredentialProvider.MsftAdTenantId) });
            var client      = new SecretClient(new Uri($"https://{KeyVaultName}.vault.azure.net/"), credentials);

            return(client);
        }
Example #4
0
        public KeyVaultClient(IConfiguration configuration)
        {
            var keyVaultUrl = configuration["KeyVault:Endpoint"];
            var cred        = new ChainedTokenCredential(new ManagedIdentityCredential(), new AzureCliCredential());

            Client = new SecretClient(new Uri(keyVaultUrl), cred);
        }
Example #5
0
        public void CustomChainedTokenCredential()
        {
            #region Snippet:CustomChainedTokenCredential
            // authenticate using managed identity if it is available otherwise use the Azure CLI to auth
            var credential = new ChainedTokenCredential(new ManagedIdentityCredential(), new AzureCliCredential());

            var eventHubProducerClient = new EventHubProducerClient("myeventhub.eventhubs.windows.net", "myhubpath", credential);
            #endregion
        }
        public async Task CredentialThrows()
        {
            var cred1    = new SimpleMockTokenCredential("scopeA", "tokenA");
            var cred2    = new ExceptionalMockTokenCredential();
            var cred3    = new SimpleMockTokenCredential("scopeB", "tokenB");
            var provider = new ChainedTokenCredential(cred1, cred2, cred3);

            Assert.AreEqual("tokenA", (await provider.GetTokenAsync(new TokenRequestContext(new string[] { "scopeA" }))).Token);
            Assert.CatchAsync <AuthenticationFailedException>(async() => await provider.GetTokenAsync(new TokenRequestContext(new string[] { "ScopeB" })));
            Assert.CatchAsync <AuthenticationFailedException>(async() => await provider.GetTokenAsync(new TokenRequestContext(new string[] { "ScopeC" })));
        }
Example #7
0
        /// <summary>
        /// Initialise a new instance of Ms Sql Connection provider using Default Azure Credentials to acquire Access Tokens.
        /// </summary>
        /// <param name="configuration">Ms Sql Configuration</param>
        /// <param name="credentialSources">List of Token Providers to use when trying to obtain a token.</param>
        public ServiceBusChainedClientProvider(MsSqlConfiguration configuration,
                                               params TokenCredential[] credentialSources) : base(configuration)
        {
            if (credentialSources == null || credentialSources.Length < 1)
            {
                throw new ArgumentNullException(nameof(credentialSources),
                                                "Credential Sources is null or empty, ensure this is set in the constructor.");
            }

            _credential = new ChainedTokenCredential(credentialSources);
        }
Example #8
0
        private async Task <string> GetConnectionStringFromKV()
        {
            // Get the credential of user assigned identity
            var credential = new ChainedTokenCredential(
                new ManagedIdentityCredential(Configuration["UserAssignedIdentityClientId"]),
                new AzureCliCredential());
            // Get secret from key vault
            var kvClient     = new SecretClient(new Uri(Configuration["KeyVaultUri"]), credential);
            var secretBundle = await kvClient.GetSecretAsync("ConnectionString");

            return(secretBundle.Value.Value);
        }
        protected async Task <TokenCredentials> GetServiceClientCredentials()
        {
            var cts   = new CancellationTokenSource();
            var creds = new ChainedTokenCredential(new[] { new AzureServiceTokenProviderCredential(TokenCredentialProvider.MsftAdTenantId) });

            AccessToken token = await creds.GetTokenAsync(new TokenRequestContext(new[]
            {
                "https://management.azure.com/.default",
            }), cts.Token);

            return(new TokenCredentials(token.Token));
        }
Example #10
0
        public static BlobContainerClient CreateClient(IConfiguration config, string section)
        {
            var options = new BlobContainerConfig();

            config.GetSection(section).Bind(options);
            var credentials = new ChainedTokenCredential(
                new ManagedIdentityCredential(),
                new AzureCliCredential()
                );

            return(new BlobContainerClient(
                       options.GetContainerUrl(), credentials));
        }
        public async Task CredentialSequenceValid()
        {
            var cred1    = new SimpleMockTokenCredential("scopeA", "tokenA");
            var cred2    = new SimpleMockTokenCredential("scopeB", "tokenB");
            var cred3    = new SimpleMockTokenCredential("scopeB", "NotToBeReturned");
            var cred4    = new SimpleMockTokenCredential("scopeC", "tokenC");
            var provider = new ChainedTokenCredential(cred1, cred2, cred3, cred4);

            Assert.AreEqual("tokenA", (await provider.GetTokenAsync(new string[] { "scopeA" })).Token);
            Assert.AreEqual("tokenB", (await provider.GetTokenAsync(new string[] { "scopeB" })).Token);
            Assert.AreEqual("tokenC", (await provider.GetTokenAsync(new string[] { "scopeC" })).Token);
            Assert.IsNull((await provider.GetTokenAsync(new string[] { "scopeD" })).Token);
        }
Example #12
0
 private static void InitializeClient()
 {
     if (_secretClient == null)
     {
         var settings = ConfigurationService.GetSection <KeyVaultSettings>();
         if (settings.IsEnabled && !string.IsNullOrEmpty(settings.KeyVaultEndpoint))
         {
             // Create a new secret client using the default credential from Azure.Identity using environment variables previously set,
             // including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.
             var cred = new ChainedTokenCredential(new ManagedIdentityCredential(), new AzureCliCredential());
             _secretClient = new SecretClient(vaultUri: new Uri(settings.KeyVaultEndpoint), cred);
         }
     }
 }
        public async Task AllCredentialSkipped()
        {
            var cred1 = new UnavailbleCredential();
            var cred2 = new UnavailbleCredential();

            var chain = new ChainedTokenCredential(cred1, cred2);

            var ex = Assert.CatchAsync <AuthenticationFailedException>(async() => await chain.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));

            Assert.IsInstanceOf(typeof(AggregateException), ex.InnerException);

            CollectionAssert.AllItemsAreInstancesOfType(((AggregateException)ex.InnerException).InnerExceptions, typeof(CredentialUnavailableException));

            await Task.CompletedTask;
        }
Example #14
0
        public async Task <string> GetAccessToken(string videoId)
        {
            // TLS 1.2 (or above) is required to send requests
            var httpHandler = new SocketsHttpHandler();

            httpHandler.SslOptions.EnabledSslProtocols |= SslProtocols.Tls12;
            var client = new HttpClient(httpHandler);

            if (apiKey == null || apiKey == "")
            {
                // Use AzureCredential to generate Azure Video Analyzer for Media Access Token
                var credential = new ChainedTokenCredential(new ManagedIdentityCredential(), new DefaultAzureCredential());

                string[] scopes = new string[1];
                scopes[0] = "https://management.azure.com/.default";
                var access_token = credential.GetToken(new TokenRequestContext(scopes));
                Console.WriteLine(access_token.Token.ToString());
                string url = $"https://management.azure.com{resourceId}/generateAccessToken?api-version=2021-10-18-preview";

                var getAccountsRequest = new HttpRequestMessage(HttpMethod.Post, url);
                getAccountsRequest.Headers.Add("Authorization", $"Bearer {access_token.Token.ToString()}");
                getAccountsRequest.Content = new StringContent("{\"permissionType\":\"Contributor\",\"scope\": \"Account\"}", Encoding.UTF8, "application/json");
                var result = await client.SendAsync(getAccountsRequest);

                string accessToken = await result.Content.ReadAsStringAsync();

                var accessTokenObj = JsonConvert.DeserializeObject <VideoAnalyzerAccessToken>(accessToken);
                accessToken = $"https://www.videoindexer.ai/embed/player/{accountId}/{videoId}?location={accountLocation}&accessToken={accessTokenObj.AccessToken}";

                return(accessToken);
            }

            else
            {
                // Use API Key for Video Indexer (or not ARM Azure Video Analyzer for Media)
                var getAccountsRequest = new HttpRequestMessage(HttpMethod.Get, $"{apiUrl}/auth/{accountLocation}/Accounts/{accountId}/Videos/{videoId}/AccessToken");
                getAccountsRequest.Headers.Add("Ocp-Apim-Subscription-Key", apiKey);
                getAccountsRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Log the request id so you can include it in case you wish to report an issue for API errors or unexpected API behavior
                var result = await client.SendAsync(getAccountsRequest);

                Console.WriteLine("Response id to log: " + result.Headers.GetValues("x-ms-request-id").FirstOrDefault()); // Log the response id so you can include it in case you wish to report an issue for API errors or unexpected API behavior
                string accessToken = (await result.Content.ReadAsStringAsync()).Trim('"');                                // The access token is returned as JSON value surrounded by double-quotes

                accessToken = $"https://www.videoindexer.ai/embed/player/{accountId}/{videoId}?location={accountLocation}&accessToken={accessToken}";

                return(accessToken);
            }
        }
Example #15
0
        // Get: /GetSecretFromKV
        public async Task <IActionResult> GetSecretFromKV()
        {
            // Get the credential of user assigned identity
            var credential = new ChainedTokenCredential(
                new ManagedIdentityCredential(_configuration["UserAssignedIdentityClientId"]),
                new AzureCliCredential());
            // Get secret from key vault
            var kvClient     = new SecretClient(new Uri(_configuration["KeyVaultUri"]), credential);
            var secretBundle = await kvClient.GetSecretAsync(_configuration["SecretName"]);

            var indexViewModel = await GetIndexViewModel();

            indexViewModel.KVSecret = secretBundle.Value.Name + ": " + secretBundle.Value.Value;

            return(View("Index", indexViewModel));
        }
        /// <summary>
        /// Initializes an implementation is <see cref="IServiceBusClientProvider"/> using Default Azure Credentials for Authentication.
        /// </summary>
        /// <param name="fullyQualifiedNameSpace">The Fully Qualified Namespace i.e. my-servicebus.azureservicebus.net</param>
        /// <param name="credentialSources">List of Token Providers to use when trying to obtain a token.</param>
        /// <exception cref="ArgumentNullException">Throws is the namespace is null</exception>
        public ServiceBusChainedClientProvider(string fullyQualifiedNameSpace, params TokenCredential[] credentialSources)
        {
            if (string.IsNullOrEmpty(fullyQualifiedNameSpace))
            {
                throw new ArgumentNullException(nameof(fullyQualifiedNameSpace),
                                                "Fully qualified Namespace is null or empty, ensure this is set in the constructor.");
            }
            else if (credentialSources == null || credentialSources.Length < 1)
            {
                throw new ArgumentNullException(nameof(credentialSources),
                                                "Credential Sources is null or empty, ensure this is set in the constructor.");
            }

            _tokenCredential         = new ChainedTokenCredential(credentialSources);
            _fullyQualifiedNameSpace = fullyQualifiedNameSpace;
        }
        public async Task CredentialSequenceValid()
        {
            var cred1    = new SimpleMockTokenCredential("scopeA", "tokenA");
            var cred2    = new SimpleMockTokenCredential("scopeB", "tokenB");
            var cred3    = new SimpleMockTokenCredential("scopeB", "NotToBeReturned");
            var cred4    = new SimpleMockTokenCredential("scopeC", "tokenC");
            var provider = new ChainedTokenCredential(cred1, cred2, cred3, cred4);

            Assert.AreEqual("tokenA", (await provider.GetTokenAsync(new TokenRequestContext(new string[] { "scopeA" }))).Token);
            Assert.AreEqual("tokenB", (await provider.GetTokenAsync(new TokenRequestContext(new string[] { "scopeB" }))).Token);
            Assert.AreEqual("tokenC", (await provider.GetTokenAsync(new TokenRequestContext(new string[] { "scopeC" }))).Token);
            var ex = Assert.CatchAsync <AuthenticationFailedException>(async() => await provider.GetTokenAsync(new TokenRequestContext(new string[] { "ScopeD" })));

            Assert.IsInstanceOf(typeof(AggregateException), ex.InnerException);

            CollectionAssert.AllItemsAreInstancesOfType(((AggregateException)ex.InnerException).InnerExceptions, typeof(CredentialUnavailableException));
        }
Example #18
0
        public async Task <List <string> > Get()
        {
            var credential = new ChainedTokenCredential(
                new AzureCliCredential(),
                new ManagedIdentityCredential()
                );
            var keyVaultClient  = new SecretClient(new Uri(configuration["KeyVaultUri"]), credential);
            var secretOperation = await keyVaultClient.GetSecretAsync("VerySecretValue");

            var secret  = secretOperation.Value.Value;
            var secret2 = configuration["SomeConfigValue"];

            return(new List <string>()
            {
                secret, secret2
            });
        }
Example #19
0
        public static async Task <GraphServiceClient> GetGraphApiClient()
        {
            var credential  = new ChainedTokenCredential(new ManagedIdentityCredential(), new AzureCliCredential());
            var accessToken = await credential.GetTokenAsync(new
                                                             TokenRequestContext(scopes : new [] { "https://graph.microsoft.com/.default" }, parentRequestId : null), default);

            var graphServiceClient = new GraphServiceClient(
                new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage
                .Headers
                .Authorization = new AuthenticationHeaderValue("bearer", accessToken.Token);

                return(Task.CompletedTask);
            }));

            return(graphServiceClient);
        }
Example #20
0
        static void Main(string[] args)
        {
            var storageUri    = Environment.GetEnvironmentVariable("APP_STORAGE_URI");
            var containerName = Environment.GetEnvironmentVariable("APP_STORAGE_CONTAINER");

            var credential = new ChainedTokenCredential(
                new ManagedIdentityCredential(),
                new EnvironmentCredential());

            var blobServiceClient = new BlobServiceClient(
                new Uri(storageUri),
                credential);

            var blobContainerClient = blobServiceClient.GetBlobContainerClient(containerName);
            var blobClient          = blobContainerClient.GetBlobClient($"{DateTime.Now.ToString("yyyy-MM-ddTHH-mm-ss")}.jpg");

            blobClient.Upload("test.jpg");
        }
Example #21
0
        public static IWebHostBuilder CreateHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context, config) =>
        {
            var builtConfig = config.Build();
            var clientId    = builtConfig["ClientId"];

            var managedIdentityCredential = string.IsNullOrEmpty(clientId)
                        ? new ManagedIdentityCredential()
                        : new ManagedIdentityCredential(clientId);

            var credential = new ChainedTokenCredential(
                new VisualStudioCredential(),
                new AzureCliCredential(),
                managedIdentityCredential);

            config.AddAzureKeyVault(new Uri(builtConfig["KeyVaultUrl"]), credential);
        })
        .UseStartup <Startup>();
        public void OnGet()
        {
            var clientId = configuration["ClientId"];

            var managedIdentityCredential = string.IsNullOrEmpty(clientId)
                ? new ManagedIdentityCredential()
                : new ManagedIdentityCredential(clientId);

            var credential = new ChainedTokenCredential(
                new VisualStudioCredential(),
                new AzureCliCredential(),
                managedIdentityCredential);

            var client = new SecretClient(vaultUri: new Uri(configuration["KeyVaultUrl"]), credential: credential);

            // Retrieve a secret using the secret client.
            FromKeyVault = client.GetSecret("KVSercret").Value.Value;

            // Retrive secret from config stored in Key Vault
            FromConfig = configuration["SomeConfigValueFromKV"];
        }
        private static async Task GetChainedTokenCredential()
        {
            string[] scopes   = new[] { "User.Read" };
            string   clientId = "d662ac70-7482-45af-9dc3-c3cde8eeede4";
            EnvironmentCredential        environmentCredential = new EnvironmentCredential();
            InteractiveBrowserCredential myBrowserCredential   = new InteractiveBrowserCredential(clientId);

            TokenCredential []          tokenCredentials            = new TokenCredential[] { environmentCredential, myBrowserCredential };
            ChainedTokenCredential      chainedTokenCredential      = new ChainedTokenCredential(tokenCredentials);
            TokenCredentialAuthProvider tokenCredentialAuthProvider = new TokenCredentialAuthProvider(chainedTokenCredential, scopes);

            //Try to get something from the Graph!!
            HttpClient          httpClient     = GraphClientFactory.Create(tokenCredentialAuthProvider);
            HttpRequestMessage  requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/users/[email protected]/");
            HttpResponseMessage response       = await httpClient.SendAsync(requestMessage);

            //Print out the response :)
            string jsonResponse = await response.Content.ReadAsStringAsync();

            Console.WriteLine(jsonResponse);
        }
Example #24
0
        static void Main(string[] args)
        {
            var serviceScope = Environment.GetEnvironmentVariable("APP_SERVICE_SCOPE");
            var serviceUri   = Environment.GetEnvironmentVariable("APP_SERVICE_URI");

            var credential = new ChainedTokenCredential(
                new ManagedIdentityCredential(),
                new EnvironmentCredential());

            var token = credential.GetToken(new TokenRequestContext(new string[] { serviceScope }));

            var functionClient = new HttpClient();

            functionClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                "Bearer",
                token.Token);

            var response = functionClient.GetAsync(serviceUri).Result;

            response.EnsureSuccessStatusCode();
        }
Example #25
0
 public AzStorageWorker(ILogger <AzStorageWorker> logger, ChainedTokenCredential tokenCredential)
 {
     _logger          = logger;
     _tokenCredential = tokenCredential;
 }