public static void TokenCredentialTest() { Guid activityId = Trace.CorrelationManager.ActivityId = Guid.NewGuid(); using DataTestUtility.AKVEventListener AKVListener = new(); ClientSecretCredential clientSecretCredential = new ClientSecretCredential(DataTestUtility.AKVTenantId, DataTestUtility.AKVClientId, DataTestUtility.AKVClientSecret); SqlColumnEncryptionAzureKeyVaultProvider akvProvider = new SqlColumnEncryptionAzureKeyVaultProvider(clientSecretCredential); byte[] encryptedCek = akvProvider.EncryptColumnEncryptionKey(DataTestUtility.AKVUrl, EncryptionAlgorithm, s_columnEncryptionKey); byte[] decryptedCek = akvProvider.DecryptColumnEncryptionKey(DataTestUtility.AKVUrl, EncryptionAlgorithm, encryptedCek); Assert.Equal(s_columnEncryptionKey, decryptedCek); ValidateAKVTraces(AKVListener.EventData, activityId); }
public void GetTokenIncorrectPassword() { var tenantId = TestEnvironment.ServicePrincipalTenantId; var clientId = TestEnvironment.ServicePrincipalClientId; var secret = "badsecret"; var options = Recording.InstrumentClientOptions(new TokenCredentialOptions()); var credential = new ClientSecretCredential(tenantId, clientId, secret, options); var tokenRequestContext = new TokenRequestContext(new[] { AzureAuthorityHosts.GetDefaultScope(AzureAuthorityHosts.AzurePublicCloud) }); // ensure we can initially acquire a token Assert.ThrowsAsync <AuthenticationFailedException>(async() => await credential.GetTokenAsync(tokenRequestContext)); }
/// <summary> /// Gets a valid token using a Service Principal or a Managed Identity /// </summary> public static async Task <TokenCredentials> GetTokenCredentialsAsync(string resource, string tenantId, AzureAuthenticationInfo authenticationInfo, System.Uri azureAuthorityHost) { Guard.NotNullOrWhitespace(resource, nameof(resource)); Guard.NotNullOrWhitespace(tenantId, nameof(tenantId)); Guard.NotNull(authenticationInfo, nameof(authenticationInfo)); TokenCredential tokenCredential; var tokenCredentialOptions = new TokenCredentialOptions { AuthorityHost = azureAuthorityHost }; switch (authenticationInfo.Mode) { case AuthenticationMode.ServicePrincipal: tokenCredential = new ClientSecretCredential(tenantId, authenticationInfo.IdentityId, authenticationInfo.Secret, tokenCredentialOptions); break; case AuthenticationMode.UserAssignedManagedIdentity: tokenCredential = new ManagedIdentityCredential(authenticationInfo.IdentityId, tokenCredentialOptions); break; case AuthenticationMode.SystemAssignedManagedIdentity: tokenCredential = new ManagedIdentityCredential(options: tokenCredentialOptions); break; default: tokenCredential = new DefaultAzureCredential(); break; } // When you reaching an endpoint, using an impersonate identity, the only endpoint available is always '/.default' // MSAL add the './default' string to your resource request behind the scene. // We have to do it here, since we are at a lower level(and we are not using MSAL; by the way) if (!resource.ToLowerInvariant().EndsWith("/.default")) { if (!resource.EndsWith("/")) { resource += "/"; } resource += ".default"; } var accessToken = await tokenCredential.GetTokenAsync(new TokenRequestContext(new[] { resource }), default); return(new TokenCredentials(accessToken.Token)); }
protected void DefaultInit() { string tenantId = _configuration["Azure:Tenant_ID"]; string clientId = _configuration["Azure:Client_ID"]; string clientSecret = _configuration["Azure:Client_Secret"]; var clientCredentials = new ClientSecretCredential(tenantId, clientId, clientSecret); var keyClient = new KeyClient(new Uri(_keyVaultUri), clientCredentials); keyClient.CreateRsaKey(new CreateRsaKeyOptions(_keyVaultKeyName)); KeyVaultKey key = keyClient.GetKey(_keyVaultKeyName); _cryptoClient = new CryptographyClient(key.Id, new DefaultAzureCredential()); }
public async Task UsesTenantIdHint( [Values(true, false)] bool usePemFile, [Values(null, TenantIdHint)] string tenantId, [Values(true)] bool allowMultiTenantAuthentication) { TestSetup(); options.AllowMultiTenantAuthentication = allowMultiTenantAuthentication; var context = new TokenRequestContext(new[] { Scope }, tenantId: tenantId); expectedTenantId = TenantIdResolver.Resolve(TenantId, context, options.AllowMultiTenantAuthentication); ClientSecretCredential client = InstrumentClient(new ClientSecretCredential(expectedTenantId, ClientId, "secret", options, null, mockMsalClient)); var token = await client.GetTokenAsync(new TokenRequestContext(MockScopes.Default)); Assert.AreEqual(token.Token, expectedToken, "Should be the expected token value"); }
public static void TokenCredentialRotationTest() { // SqlClientCustomTokenCredential implements a legacy authentication callback to request the access token from the client-side. SqlColumnEncryptionAzureKeyVaultProvider oldAkvProvider = new SqlColumnEncryptionAzureKeyVaultProvider(new SqlClientCustomTokenCredential()); ClientSecretCredential clientSecretCredential = new ClientSecretCredential(DataTestUtility.AKVTenantId, DataTestUtility.AKVClientId, DataTestUtility.AKVClientSecret); SqlColumnEncryptionAzureKeyVaultProvider newAkvProvider = new SqlColumnEncryptionAzureKeyVaultProvider(clientSecretCredential); byte[] encryptedCekWithNewProvider = newAkvProvider.EncryptColumnEncryptionKey(DataTestUtility.AKVUrl, EncryptionAlgorithm, s_columnEncryptionKey); byte[] decryptedCekWithOldProvider = oldAkvProvider.DecryptColumnEncryptionKey(DataTestUtility.AKVUrl, EncryptionAlgorithm, encryptedCekWithNewProvider); Assert.Equal(s_columnEncryptionKey, decryptedCekWithOldProvider); byte[] encryptedCekWithOldProvider = oldAkvProvider.EncryptColumnEncryptionKey(DataTestUtility.AKVUrl, EncryptionAlgorithm, s_columnEncryptionKey); byte[] decryptedCekWithNewProvider = newAkvProvider.DecryptColumnEncryptionKey(DataTestUtility.AKVUrl, EncryptionAlgorithm, encryptedCekWithOldProvider); Assert.Equal(s_columnEncryptionKey, decryptedCekWithNewProvider); }
/* * Program migrates a client side encrypted blob to server side encryption using an encryption scope with Microsoft managed keys * * NOTE: This program requires the following to be stored in the App.Config file: * Azure Active Directory Tenant ID - tenantId * Service Principal Application ID - clientId * Service Principal Password - clientSecret * Storage Account Connection String- connectionString * Client Side Key Vault Key Uri - clientSideKeyVaultKeyUri * Key Wrap Algorithm - keyWrapAlgorithm * Container Name - containerName * Blob Name - blobName * Blob Name After Migration - blobNameAfterMigration * Encryption Scope Name - encryptionScopeName */ static void Main() { //Credentials of Service Principal TokenCredential credential = new ClientSecretCredential( Constants.TenantId, Constants.ClientId, Constants.ClientSecret ); //File Path for local file used to download and reupload string localPath = "./data" + Guid.NewGuid().ToString() + "/"; Directory.CreateDirectory(localPath); string localFilePath = Path.Combine(localPath, Constants.BlobName); //Get Uri for Key Vault key Uri keyVaultKeyUri = new Uri(Constants.ClientSideKeyVaultKeyUri); //Create CryptographyClient using Key Vault Key CryptographyClient cryptographyClient = new CryptographyClient(keyVaultKeyUri, credential); //Set up Client Side Encryption Options used for Client Side Encryption ClientSideEncryptionOptions clientSideOptions = new ClientSideEncryptionOptions(ClientSideEncryptionVersion.V1_0) { KeyEncryptionKey = cryptographyClient, KeyWrapAlgorithm = Constants.KeyWrapAlgorithm }; try { //Convert Client Side Encryption Blob to Server Side Encrytion with Microsoft Managed Keys EncryptWithMicrosoftManagedKey( Constants.ConnectionString, Constants.ContainerName, Constants.BlobName, Constants.BlobNameAfterMigration, localFilePath, clientSideOptions, Constants.EncryptionScopeName); } finally { //Delete downloaded files CleanUp(localPath); } Console.WriteLine("Completed migration to Microsoft Managed Key Server Side Encryption"); }
public async Task VerifyClientSecretCredentialRequestAsync() { var response = new MockResponse(200); var expectedToken = "mock-msi-access-token"; response.SetContent($"{{ \"access_token\": \"{expectedToken}\", \"expires_in\": 3600 }}"); var mockTransport = new MockTransport(response); var options = new TokenCredentialOptions() { Transport = mockTransport }; var expectedTenantId = Guid.NewGuid().ToString(); var expectedClientId = Guid.NewGuid().ToString(); var expectedClientSecret = "secret"; ClientSecretCredential client = InstrumentClient(new ClientSecretCredential(expectedTenantId, expectedClientId, expectedClientSecret, options)); AccessToken actualToken = await client.GetTokenAsync(new TokenRequestContext(MockScopes.Default)); Assert.AreEqual(expectedToken, actualToken.Token); MockRequest request = mockTransport.SingleRequest; Assert.IsTrue(request.Content.TryComputeLength(out long contentLen)); var content = new byte[contentLen]; await request.Content.WriteToAsync(new MemoryStream(content), default); Assert.IsTrue(TryParseFormEncodedBody(content, out Dictionary <string, string> parsedBody)); Assert.IsTrue(parsedBody.TryGetValue("response_type", out string responseType) && responseType == "token"); Assert.IsTrue(parsedBody.TryGetValue("grant_type", out string grantType) && grantType == "client_credentials"); Assert.IsTrue(parsedBody.TryGetValue("client_id", out string actualClientId) && actualClientId == expectedClientId); Assert.IsTrue(parsedBody.TryGetValue("client_secret", out string actualClientSecret) && actualClientSecret == "secret"); Assert.IsTrue(parsedBody.TryGetValue("scope", out string actualScope) && actualScope == MockScopes.Default.ToString()); }
private static async Task GetClientSecretCredentialCredential() { string[] scopes = new[] { "https://graph.microsoft.com/.default" };//see https://stackoverflow.com/questions/51781898/aadsts70011-the-provided-value-for-the-input-parameter-scope-is-not-valid/51789899 ClientSecretCredential clientSecretCredential = new ClientSecretCredential("9cacb64e-358b-418b-967a-3cabc2a0ea95", "cdc858be-9aaa-4339-94e1-86414d05a056", "AI6ju0@Jn4ECkg1rv[QOrW_.hn4_VD26"); TokenCredentialAuthProvider tokenCredentialAuthProvider = new TokenCredentialAuthProvider(clientSecretCredential, 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); }
//MSAL doesn't cache Service Principal into msal.cache public override Task <IAccessToken> Authenticate(AuthenticationParameters parameters, CancellationToken cancellationToken) { var spParameters = parameters as ServicePrincipalParameters; var onPremise = spParameters.Environment.OnPremise; var tenantId = onPremise ? AdfsTenant : (string.Equals(parameters.TenantId, OrganizationsTenant, StringComparison.OrdinalIgnoreCase) ? null : parameters.TenantId); var resource = spParameters.Environment.GetEndpoint(spParameters.ResourceId) ?? spParameters.ResourceId; var scopes = AuthenticationHelpers.GetScope(onPremise, resource); var clientId = spParameters.ApplicationId; var authority = spParameters.Environment.ActiveDirectoryAuthority; var requestContext = new TokenRequestContext(scopes); var options = new ClientCertificateCredentialOptions() { AuthorityHost = new Uri(authority) }; if (!string.IsNullOrEmpty(spParameters.Thumbprint)) { //Service Principal with Certificate var certificate = AzureSession.Instance.DataStore.GetCertificate(spParameters.Thumbprint); ClientCertificateCredential certCredential = new ClientCertificateCredential(tenantId, spParameters.ApplicationId, certificate, options); return(MsalAccessToken.GetAccessTokenAsync( certCredential, requestContext, cancellationToken, spParameters.TenantId, spParameters.ApplicationId)); } else if (spParameters.Secret != null) { // service principal with secret var secretCredential = new ClientSecretCredential(tenantId, spParameters.ApplicationId, spParameters.Secret.ConvertToString(), options); return(MsalAccessToken.GetAccessTokenAsync( secretCredential, requestContext, cancellationToken, spParameters.TenantId, spParameters.ApplicationId)); } else { throw new MsalException(MsalError.AuthenticationFailed, string.Format(AuthenticationFailedMessage, clientId)); } }
/// <summary> /// Get a service client for ADLS Gen2 [Blob endpoint] and use AAD token for authorization /// </summary> public BlobServiceClient GetBlobServiceClient(string accountName, string clientID, string clientSecret, string tenantID, BlobClientOptions options = null) { TokenCredential credential = new ClientSecretCredential( tenantID, clientID, clientSecret, new TokenCredentialOptions()); string dfsUri = "https://" + accountName + ".blob.core.windows.net"; if (options == null) { return(new BlobServiceClient(new Uri(dfsUri), credential)); } else { return(new BlobServiceClient(new Uri(dfsUri), credential, options)); } }
private async static Task <Uri> GetUserDelegationSasBlob(string containerName, string blobName) { // Construct the blob endpoint from the account name. string blobEndpoint = string.Format("https://{0}.blob.core.windows.net", Settings.StorageAccount); var credential = new ClientSecretCredential( Settings.TenantId, Settings.ClientId, Settings.ClientSecret, new TokenCredentialOptions()); // Create a new Blob service client with Azure AD credentials. BlobServiceClient blobClient = new BlobServiceClient(new Uri(blobEndpoint), credential); // Get a user delegation key for the Blob service that's valid for seven days. // You can use the key to generate any number of shared access signatures over the lifetime of the key. UserDelegationKey key = await blobClient.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(7)); // Create a SAS token that's valid for one hour. BlobSasBuilder sasBuilder = new BlobSasBuilder() { BlobContainerName = containerName, BlobName = blobName, Resource = "b", StartsOn = DateTimeOffset.UtcNow, ExpiresOn = DateTimeOffset.UtcNow.AddHours(1) }; // Specify read permissions for the SAS. sasBuilder.SetPermissions(BlobSasPermissions.Read); // Use the key to get the SAS token. string sasToken = sasBuilder.ToSasQueryParameters(key, Settings.StorageAccount).ToString(); // Construct the full URI, including the SAS token. UriBuilder fullUri = new UriBuilder() { Scheme = "https", Host = string.Format("{0}.blob.core.windows.net", Settings.StorageAccount), Path = string.Format("{0}/{1}", containerName, blobName), Query = sasToken }; return(fullUri.Uri); }
/// <summary> /// Create Azure Blob Storage with AAD authentication /// </summary> /// <param name="factory"></param> /// <param name="accountName"></param> /// <param name="tenantId"></param> /// <param name="applicationId"></param> /// <param name="applicationSecret"></param> /// <param name="activeDirectoryAuthEndpoint"></param> /// <returns></returns> public static IAzureBlobStorage AzureBlobStorageWithAzureAd(this IBlobStorageFactory factory, string accountName, string tenantId, string applicationId, string applicationSecret, string activeDirectoryAuthEndpoint = "https://login.microsoftonline.com/") { if (accountName is null) { throw new ArgumentNullException(nameof(accountName)); } if (tenantId is null) { throw new ArgumentNullException(nameof(tenantId)); } if (applicationId is null) { throw new ArgumentNullException(nameof(applicationId)); } if (applicationSecret is null) { throw new ArgumentNullException(nameof(applicationSecret)); } if (activeDirectoryAuthEndpoint is null) { throw new ArgumentNullException(nameof(activeDirectoryAuthEndpoint)); } // Create a token credential that can use our Azure Active // Directory application to authenticate with Azure Storage TokenCredential credential = new ClientSecretCredential( tenantId, applicationId, applicationSecret, new TokenCredentialOptions() { AuthorityHost = new Uri(activeDirectoryAuthEndpoint) }); // Create a client that can authenticate using our token credential var client = new BlobServiceClient(GetServiceUri(accountName), credential); return(new AzureBlobStorage(client, accountName)); }
public GraphApiService() { //Get Environment Variable Configuration this.clientId = Environment.GetEnvironmentVariable("GraphApiAppClientId"); this.clientSecret = Environment.GetEnvironmentVariable("GraphApiAppClientSecret"); this.tenantId = Environment.GetEnvironmentVariable("GraphApiAppTenantId"); var scopes = new[] { "https://graph.microsoft.com/.default" }; var options = new TokenCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud, }; var clientSecretCredential = new ClientSecretCredential( tenantId, clientId, clientSecret, options); graphClient = new GraphServiceClient(clientSecretCredential, scopes); }
public async Task EnvironmentCredentialAuthenticationFailedException() { string expectedInnerExMessage = Guid.NewGuid().ToString(); var mockMsalClient = new MockMsalConfidentialClient(new MockClientException(expectedInnerExMessage)); ClientSecretCredential innerCred = new ClientSecretCredential(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), CredentialPipeline.GetInstance(null), mockMsalClient); var credential = InstrumentClient(new EnvironmentCredential(CredentialPipeline.GetInstance(null), innerCred)); var ex = Assert.ThrowsAsync <AuthenticationFailedException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default))); Assert.IsInstanceOf(typeof(MockClientException), ex.InnerException); Assert.AreEqual(expectedInnerExMessage, ex.InnerException.Message); await Task.CompletedTask; }
public async Task VerifyClientSecretCredentialExceptionAsync() { string expectedInnerExMessage = Guid.NewGuid().ToString(); var mockAadClient = new MockAadIdentityClient(() => { throw new MockClientException(expectedInnerExMessage); }); ClientSecretCredential credential = InstrumentClient(new ClientSecretCredential(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), CredentialPipeline.GetInstance(null), mockAadClient)); var ex = Assert.ThrowsAsync <AuthenticationFailedException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default))); Assert.IsNotNull(ex.InnerException); Assert.IsInstanceOf(typeof(MockClientException), ex.InnerException); Assert.AreEqual(expectedInnerExMessage, ex.InnerException.Message); await Task.CompletedTask; }
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((context, config) => { //This is how the application is connected to the Azure Key Vault var builtConfiguration = config.Build(); string kvURL = builtConfiguration["KeyVaultConfig:KVUrl"]; string tenantId = builtConfiguration["KeyVaultConfig:TenantId"]; string clientId = builtConfiguration["KeyVaultConfig:ClientId"]; string clientSecret = builtConfiguration["KeyVaultConfig:ClientSecretId"]; var credential = new ClientSecretCredential(tenantId, clientId, clientSecret); var client = new SecretClient(new Uri(kvURL), credential); config.AddAzureKeyVault(client, new AzureKeyVaultConfigurationOptions()); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup <Startup>(); });
public void VerifyMsalClientRegionalAuthority() { RegionalAuthority?[] authorities = { null, RegionalAuthority.AutoDiscoverRegion, RegionalAuthority.USWest }; foreach (RegionalAuthority?regionalAuthority in authorities) { var expectedTenantId = Guid.NewGuid().ToString(); var expectedClientId = Guid.NewGuid().ToString(); var expectedClientSecret = Guid.NewGuid().ToString(); var cred = new ClientSecretCredential(expectedTenantId, expectedClientId, expectedClientSecret, new ClientSecretCredentialOptions { RegionalAuthority = regionalAuthority }); Assert.AreEqual(regionalAuthority, cred.Client.RegionalAuthority); } }
/// <summary> /// Load a certificate (with private key) from Azure Key Vault /// /// Getting a certificate with private key is a bit of a pain, but the code below solves it. /// /// Get the private key for Key Vault certificate /// https://github.com/heaths/azsdk-sample-getcert /// /// See also these GitHub issues: /// https://github.com/Azure/azure-sdk-for-net/issues/12742 /// https://github.com/Azure/azure-sdk-for-net/issues/12083 /// </summary> /// <param name="config"></param> /// <param name="certificateName"></param> /// <returns></returns> public static X509Certificate2 LoadCertificate(IConfiguration config, string certificateName) { string vaultUrl = config["Vault:Url"] ?? ""; string clientId = config["Vault:ClientId"] ?? ""; string tenantId = config["Vault:TenantId"] ?? ""; string secret = config["Vault:Secret"] ?? ""; Console.WriteLine($"Loading certificate '{certificateName}' from Azure Key Vault"); var credentials = new ClientSecretCredential(tenantId: tenantId, clientId: clientId, clientSecret: secret); var certClient = new CertificateClient(new Uri(vaultUrl), credentials); var secretClient = new SecretClient(new Uri(vaultUrl), credentials); var cert = GetCertificateAsync(certClient, secretClient, certificateName); Console.WriteLine("Certificate loaded"); return(cert); }
public Fixture() { TestSiteName = "Test_test"; Environment = new TestEnvironment(); var configuration = TestHelpers.GetTestConfiguration(); BlobConnectionString = configuration.GetWebJobsConnectionString(ConnectionStringNames.Storage); KeyVaultUri = configuration.GetWebJobsConnectionString(EnvironmentSettingNames.AzureWebJobsSecretStorageKeyVaultUri); KeyVaultClientId = configuration.GetWebJobsConnectionString(EnvironmentSettingNames.AzureWebJobsSecretStorageKeyVaultClientId); KeyVaultClientSecret = configuration.GetWebJobsConnectionString(EnvironmentSettingNames.AzureWebJobsSecretStorageKeyVaultClientSecret); KeyVaultTenantId = configuration.GetWebJobsConnectionString(EnvironmentSettingNames.AzureWebJobsSecretStorageKeyVaultTenantId); var credential = new ClientSecretCredential(KeyVaultTenantId, KeyVaultClientId, KeyVaultClientSecret); SecretClient = new SecretClient(new Uri(KeyVaultUri), credential); AzureBlobStorageProvider = TestHelpers.GetAzureBlobStorageProvider(configuration); }
/// <summary> /// Create notification groups for failures in scheduled builds /// </summary> /// <param name="organization">Azure DevOps Organization</param> /// <param name="project">Name of the DevOps project</param> /// <param name="pathPrefix">Path prefix to include pipelines (e.g. "\net")</param> /// <param name="tokenVariableName">Environment variable token name (e.g. "SYSTEM_ACCESSTOKEN")</param> /// <param name="aadAppIdVar">AAD App ID environment variable name (OpensourceAPI access)</param> /// <param name="aadAppSecretVar">AAD App Secret environment variable name (OpensourceAPI access)</param> /// <param name="aadTenantVar">AAD Tenant environment variable name (OpensourceAPI access)</param> /// <param name="selectionStrategy">Pipeline selection strategy</param> /// <param name="dryRun">Prints changes but does not alter any objects</param> /// <returns></returns> static async Task Main( string organization, string project, string pathPrefix, string tokenVariableName, string aadAppIdVar, string aadAppSecretVar, string aadTenantVar, PipelineSelectionStrategy selectionStrategy = PipelineSelectionStrategy.Scheduled, bool dryRun = false) { var devOpsToken = Environment.GetEnvironmentVariable(tokenVariableName); var devOpsCreds = new VssBasicCredential("nobody", devOpsToken); var devOpsConnection = new VssConnection(new Uri($"https://dev.azure.com/{organization}/"), devOpsCreds); #pragma warning disable CS0618 // Type or member is obsolete var loggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(config => { config.IncludeScopes = true; }); }); #pragma warning restore CS0618 // Type or member is obsolete var devOpsServiceLogger = loggerFactory.CreateLogger <AzureDevOpsService>(); var notificationConfiguratorLogger = loggerFactory.CreateLogger <NotificationConfigurator>(); var devOpsService = new AzureDevOpsService(devOpsConnection, devOpsServiceLogger); var gitHubService = new GitHubService(loggerFactory.CreateLogger <GitHubService>()); var credential = new ClientSecretCredential( Environment.GetEnvironmentVariable(aadTenantVar), Environment.GetEnvironmentVariable(aadAppIdVar), Environment.GetEnvironmentVariable(aadAppSecretVar)); var githubToAadResolver = new GitHubToAADConverter( credential, loggerFactory.CreateLogger <GitHubToAADConverter>() ); var configurator = new NotificationConfigurator(devOpsService, gitHubService, notificationConfiguratorLogger); await configurator.ConfigureNotifications( project, pathPrefix, githubToAadResolver, persistChanges : !dryRun, strategy : selectionStrategy); }
public AzureStorageService( IConfiguration configuration) { var storageSection = configuration.GetSection("AzureStorage"); var azureAdInfo = new { TenantId = storageSection["TenantId"], ClientId = storageSection["ClientId"], ClientSecret = storageSection["ClientSecret"], }; var credential = new ClientSecretCredential(azureAdInfo.TenantId, azureAdInfo.ClientId, azureAdInfo.ClientSecret); var storageInfo = new { AccountName = storageSection["AccountName"], ContainerName = storageSection["ContainerName"] }; _accountName = storageInfo.AccountName; _containerName = storageInfo.ContainerName; _client = new BlobServiceClient(new Uri($"https://{_accountName}.blob.core.windows.net/"), credential); // make sure the container exists if (!_client.GetBlobContainerClient(_containerName).Exists().Value) { // the below code prevents handles when 2 instances start simulatenously // and one has already created the container try { _client.CreateBlobContainer(_containerName, PublicAccessType.None); } catch (Azure.RequestFailedException ex) { // rethrow if anything OTHER than ContainerAlreadyExists if (ex.ErrorCode != BlobErrorCode.ContainerAlreadyExists) { throw ex; } // if error was ContainerAlreadyExists, ignore as we can now be sure that the container exists } } }
internal static TokenCredential GetAzureCredential(IHostEnvironment environment, IConfiguration configuration) { TokenCredential azureCredential; if (environment.IsDevelopment()) { azureCredential = new ClientSecretCredential( configuration.GetValue <string>("ServicePrincipalTenantId"), configuration.GetValue <string>("ServicePrincipalClientId"), configuration.GetValue <string>("ServicePrincipalClientSecret") ); } else { azureCredential = new DefaultAzureCredential(); } return(azureCredential); }
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((context, config) => { var builtConfig = config.AddEnvironmentVariables().Build(); var vaultUri = new Uri($"https://{builtConfig["KeyVaultName"]}.vault.azure.net/"); var azureTenantId = builtConfig["AzureADDirectoryId"]; var azureClientId = builtConfig["AzureADApplicationId"]; var azureSecretId = builtConfig["AzureADApplicationSecret"]; var credential = new ClientSecretCredential(azureTenantId, azureClientId, azureSecretId); config.AddAzureKeyVault(vaultUri, credential, new KeyVaultSecretManager()); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup <Startup>(); });
/// <summary> /// Azure Key Vault secrets. /// </summary> /// <param name="factory">The factory.</param> /// <param name="vaultUri">The vault URI.</param> /// <param name="azureAadClientId">The azure aad client identifier.</param> /// <param name="azureAadClientSecret">The azure aad client secret.</param> /// <returns></returns> public static IBlobStorage AzureKeyVault(this IBlobStorageFactory factory, Uri vaultUri, string tenantId, string applicationId, string applicationSecret, string activeDirectoryAuthEndpoint = "https://login.microsoftonline.com/") { TokenCredential credential = new ClientSecretCredential( tenantId, applicationId, applicationSecret, new TokenCredentialOptions() { AuthorityHost = new Uri(activeDirectoryAuthEndpoint) }); return(new AzureKeyVaultBlobStorageProvider(vaultUri, credential)); }
public async Task <ErrorOr <AzureKeyVaultMaterializedConfiguration> > Materialize(AzureKeyVaultSignConfigurationSet configuration) { TokenCredential credential; if (configuration.ManagedIdentity) { credential = new DefaultAzureCredential(); } else if (!string.IsNullOrWhiteSpace(configuration.AzureAccessToken)) { credential = new AccessTokenCredential(configuration.AzureAccessToken); } else { credential = new ClientSecretCredential(configuration.AzureTenantId, configuration.AzureClientId, configuration.AzureClientSecret); } X509Certificate2 certificate; KeyVaultCertificateWithPolicy azureCertificate; try { var certClient = new CertificateClient(configuration.AzureKeyVaultUrl, credential); _logger.LogTrace($"Retrieving certificate {configuration.AzureKeyVaultCertificateName}."); azureCertificate = (await certClient.GetCertificateAsync(configuration.AzureKeyVaultCertificateName).ConfigureAwait(false)).Value; _logger.LogTrace($"Retrieved certificate {configuration.AzureKeyVaultCertificateName}."); certificate = new X509Certificate2(azureCertificate.Cer); } catch (Exception e) { _logger.LogError($"Failed to retrieve certificate {configuration.AzureKeyVaultCertificateName} from Azure Key Vault. Please verify the name of the certificate and the permissions to the certificate. Error message: {e.Message}."); _logger.LogTrace(e.ToString()); return(e); } var keyId = azureCertificate.KeyId; return(new AzureKeyVaultMaterializedConfiguration(credential, certificate, keyId)); }
/// <summary> /// Configures the application. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to configure.</param> /// <param name="context">The <see cref="HostBuilderContext"/> to use.</param> /// <returns> /// The <see cref="IConfigurationBuilder"/> passed as the value of <paramref name="builder"/>. /// </returns> public static IConfigurationBuilder ConfigureApplication(this IConfigurationBuilder builder, HostBuilderContext context) { builder.AddApplicationInsightsSettings(developerMode: context.HostingEnvironment.IsDevelopment()); // Build the configuration so far IConfiguration config = builder.Build(); // Get the settings for Azure Key Vault string vault = config["AzureKeyVault:Uri"]; string clientId = config["AzureKeyVault:ClientId"]; string clientSecret = config["AzureKeyVault:ClientSecret"]; string tenantId = config["AzureKeyVault:TenantId"]; // Can Managed Service Identity be used instead of direct Key Vault integration? bool canUseMsi = !string.Equals(config["WEBSITE_DISABLE_MSI"], bool.TrueString, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(config["MSI_ENDPOINT"]) && !string.IsNullOrEmpty(config["MSI_SECRET"]); bool canUseKeyVault = !string.IsNullOrEmpty(vault) && (canUseMsi || (!string.IsNullOrEmpty(clientId) && !string.IsNullOrEmpty(clientSecret) && !string.IsNullOrEmpty(tenantId))); if (canUseKeyVault) { var manager = new AzureEnvironmentSecretManager(config.AzureEnvironment()); TokenCredential credential; if (canUseMsi) { credential = new ManagedIdentityCredential(); } else { credential = new ClientSecretCredential(tenantId, clientId, clientSecret); } builder.AddAzureKeyVault(new Uri(vault), credential, manager); } return(builder); }
public async Task ActiveDirectoryAuthAsync() { // Create a token credential that can use our Azure Active // Directory application to authenticate with Azure Storage TokenCredential credential = new ClientSecretCredential( ActiveDirectoryTenantId, ActiveDirectoryApplicationId, ActiveDirectoryApplicationSecret, new TokenCredentialOptions() { AuthorityHost = ActiveDirectoryAuthEndpoint }); // Create a client that can authenticate using our token credential BlobServiceClient service = new BlobServiceClient(ActiveDirectoryBlobUri, credential); // Make a service request to verify we've successfully authenticated await service.GetPropertiesAsync(); }
public async Task VerifyClientSecretRequestFailedAsync() { var response = new MockResponse(400); response.SetContent($"{{ \"error_code\": \"InvalidSecret\", \"message\": \"The specified client_secret is incorrect\" }}"); var mockTransport = new MockTransport(response); var options = new TokenCredentialOptions() { Transport = mockTransport }; var expectedTenantId = Guid.NewGuid().ToString(); var expectedClientId = Guid.NewGuid().ToString(); var expectedClientSecret = "secret"; ClientSecretCredential client = InstrumentClient(new ClientSecretCredential(expectedTenantId, expectedClientId, expectedClientSecret, options)); Assert.ThrowsAsync <AuthenticationFailedException>(async() => await client.GetTokenAsync(new TokenRequestContext(MockScopes.Default))); await Task.CompletedTask; }
/// <summary> /// Illustrates how to construct a <see cref="DigitalTwinsClient"/> with the fewest required parameters, /// using the <see cref="ClientSecretCredential"/> implementation of <see cref="Azure.Core.TokenCredential"/>. /// </summary> /// <param name="tenantId">The Id of the tenant of the application Id.</param> /// <param name="clientId">The application Id.</param> /// <param name="clientSecret">A client secret for the application Id.</param> /// <param name="adtEndpoint">The endpoint of the digital twins instance.</param> private static DigitalTwinsClient GetDigitalTwinsClient(string tenantId, string clientId, string clientSecret, string adtEndpoint) { #region Snippet:DigitalTwinSampleCreateServiceClient var clientSecretCredential = new ClientSecretCredential( tenantId, clientId, clientSecret, new TokenCredentialOptions { AuthorityHost = KnownAuthorityHosts.AzureCloud }); var dtClient = new DigitalTwinsClient( new Uri(adtEndpoint), clientSecretCredential); #endregion Snippet:DigitalTwinSampleCreateServiceClient return(dtClient); }