public async Task VerifyClientCertificateRequestFailedAsync(bool usePemFile) { 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 certificatePath = Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", "cert.pfx"); var certificatePathPem = Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", "cert.pem"); var mockCert = new X509Certificate2(certificatePath, "password"); ClientCertificateCredential credential = InstrumentClient( usePemFile ? new ClientCertificateCredential(expectedTenantId, expectedClientId, certificatePathPem, options) : new ClientCertificateCredential(expectedTenantId, expectedClientId, mockCert, options) ); Assert.ThrowsAsync <AuthenticationFailedException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default))); await Task.CompletedTask; }
public (ClientSecretCredential secretCredential, ClientCertificateCredential certCredential) GetClientCredential( Func <string, string> getSecretFromVault, Func <string, X509Certificate2> getCertFromVault) { var secretOrCert = GetClientSecretOrCert(getSecretFromVault, getCertFromVault); if (secretOrCert.secret != null) { var credential = new ClientSecretCredential( settings.TenantId, settings.ClientId, secretOrCert.secret, new TokenCredentialOptions { AuthorityHost = new Uri(AadSettings.MicrosoftAadLoginUrl) }); return(credential, null); } else { var credential = new ClientCertificateCredential( settings.TenantId, settings.ClientId, secretOrCert.cert, new TokenCredentialOptions { AuthorityHost = new Uri(AadSettings.MicrosoftAadLoginUrl) }); return(null, credential); } }
public async Task VerifyClientCertificateCredentialExceptionAsync(bool usePemFile) { string expectedInnerExMessage = Guid.NewGuid().ToString(); var mockAadClient = new MockAadIdentityClient(() => { throw new MockClientException(expectedInnerExMessage); }); var expectedTenantId = Guid.NewGuid().ToString(); var expectedClientId = Guid.NewGuid().ToString(); var certificatePath = Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", "cert.pfx"); var certificatePathPem = Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", "cert.pem"); var mockCert = new X509Certificate2(certificatePath, "password"); ClientCertificateCredential credential = InstrumentClient( usePemFile ? new ClientCertificateCredential(expectedTenantId, expectedClientId, certificatePathPem, CredentialPipeline.GetInstance(null), mockAadClient) : new ClientCertificateCredential(expectedTenantId, expectedClientId, mockCert, 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 void Main() { ClientCertificateCredential certificateCredential = new ClientCertificateCredential( "TenantID", "ClientID", "C:\\Path\\To\\Private\\Key.pem" ); // Storage accounts blob service URI Uri accountUri = new Uri("https://STORAGEACCOUNT.blob.core.windows.net/"); // Set the container name string containerName = "testcontainer"; // Create blob service client using certificate credentials BlobServiceClient blobService = new BlobServiceClient(accountUri, certificateCredential); // Get a service client to the container BlobContainerClient containerClient = blobService.GetBlobContainerClient(containerName); // Get and print names of all the blobs foreach (BlobItem blob in containerClient.GetBlobs()) { Console.WriteLine(blob.Name); } Console.Read(); }
private MarketplaceMeteringClient GetMarketplaceMeteringClient(bool useCert = false) { TokenCredential creds; if (useCert) { var password = this.config["certPassword"]; var certCollection = new X509Certificate2Collection(); var certBytes = this.ReadBytes(); certCollection.Import(certBytes, password, X509KeyStorageFlags.PersistKeySet); var cert = certCollection[0]; creds = new ClientCertificateCredential(this.config["TenantId"], this.config["ClientId"], cert); } else { creds = new ClientSecretCredential(this.config["TenantId"], this.config["ClientId"], this.config["clientSecret"]); } return(new MarketplaceMeteringClient(creds, this.GetMarketplaceMeteringClientOptions())); }
private static TokenCredential GetTokenCredential(string tenantId, string clientId, string clientCertThumbprint) { ClientCertificateCredential clientCertificateCredential; clientCertificateCredential = new ClientCertificateCredential(tenantId, clientId, Program.GetCertificate(clientCertThumbprint)); return(clientCertificateCredential); }
private (Uri uri, ClientCertificateCredential clientCredentials) InitializeKeyVaultLocally() { var keyvaultUri = new Uri(Configuration["KeyVaultUrl"]); var clientCredentials = new ClientCertificateCredential(Configuration["KeyVaultTenantId"], Configuration["KeyVaultClientId"], GetCertificate(Configuration["CertThumbPrint"])); return(keyvaultUri, clientCredentials); }
public async Task <string> GetSecretAsApplicationUsingClientCertificateAsync() { logger.LogInformation("----- Client Certificate Async"); SecretClientOptions options = KeyVaultUtility.CreateSecretClientOptions(); var keyVault = keyVaultConfiguration.Url; var credential = new ClientCertificateCredential( applicationConfiguration.TenantId, applicationConfiguration.ClientId, KeyVaultUtility.GetCertificate(applicationConfiguration.Thumbprint)); var client = new SecretClient(new Uri(keyVault), credential, options); KeyVaultSecret secret = null; try { secret = await client.GetSecretAsync(keyVaultConfiguration.SecretName); return(secret.Value); } catch (Exception ex) { logger.LogError(ex, "Failed to get secret as client sertificate"); throw; } }
private MarketplaceMeteringClient GetMarketplaceMeteringClient(bool useCert = false) { TokenCredential creds; if (useCert) { var password = this.config["certPassword"]; var filePath = this.config["certFilePath"]; var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); var certCollection = new X509Certificate2Collection(); certCollection.Import(filePath, password, X509KeyStorageFlags.PersistKeySet); var cert = certCollection[0]; creds = new ClientCertificateCredential(this.config["TenantId"], this.config["ClientId"], cert); } else { creds = new ClientSecretCredential(this.config["TenantId"], this.config["ClientId"], this.config["clientSecret"]); } return(new MarketplaceMeteringClient(creds, this.GetMarketplaceMeteringClientOptions())); }
public async Task FromX509Certificate2() { var tenantId = TestEnvironment.ServicePrincipalTenantId; var clientId = TestEnvironment.ServicePrincipalClientId; var cert = new X509Certificate2(TestEnvironment.ServicePrincipalCertificatePfxPath); var options = InstrumentClientOptions(new TokenCredentialOptions()); var credential = new ClientCertificateCredential(tenantId, clientId, cert, options); var tokenRequestContext = new TokenRequestContext(new[] { AzureAuthorityHosts.GetDefaultScope(AzureAuthorityHosts.AzurePublicCloud) }); // ensure we can initially acquire a token AccessToken token = await credential.GetTokenAsync(tokenRequestContext); Assert.IsNotNull(token.Token); // ensure subsequent calls before the token expires are served from the token cache AccessToken cachedToken = await credential.GetTokenAsync(tokenRequestContext); Assert.AreEqual(token.Token, cachedToken.Token); // ensure new credentials don't share tokens from the cache var credential2 = new ClientCertificateCredential(tenantId, clientId, cert, options); AccessToken token2 = await credential2.GetTokenAsync(tokenRequestContext); // this assert is conditional because the access token is scrubbed in the recording so they will never be different if (Mode != RecordedTestMode.Playback && Mode != RecordedTestMode.None) { Assert.AreNotEqual(token.Token, token2.Token); } }
private ClientCertificateCredential GetCertificateCredential() { X509Certificate2 cert = LoadCertificate(_keyVaultConfig.CertificateThumbprint); var clientCertificateCredential = new ClientCertificateCredential( _keyVaultConfig.TenantId, _keyVaultConfig.ClientId, cert); return(clientCertificateCredential); }
public void CreateWithPath() { string tenantId = "00000000-0000-0000-0000-00000000"; string clientId = "00000000-0000-0000-0000-00000000"; #region Snippet:Identity_CertificateCredenetial_CreateWithPath var credential = new ClientCertificateCredential(tenantId, clientId, "./certs/cert.pfx"); #endregion }
public async Task VerifyClientCertificateRequestAsync(bool usePemFile) { 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 certificatePath = Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", "cert.pfx"); var certificatePathPem = Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", "cert.pem"); var mockCert = new X509Certificate2(certificatePath, "password"); ClientCertificateCredential credential = InstrumentClient( usePemFile ? new ClientCertificateCredential(expectedTenantId, expectedClientId, certificatePathPem, options) : new ClientCertificateCredential(expectedTenantId, expectedClientId, mockCert, options) ); AccessToken actualToken = await credential.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_assertion_type", out string assertionType) && assertionType == "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"); Assert.IsTrue(parsedBody.TryGetValue("client_id", out string actualClientId) && actualClientId == expectedClientId); Assert.IsTrue(parsedBody.TryGetValue("scope", out string actualScope) && actualScope == MockScopes.Default.ToString()); Assert.IsTrue(parsedBody.TryGetValue("client_assertion", out string clientAssertion)); // var header VerifyClientAssertion(clientAssertion, expectedTenantId, expectedClientId, mockCert); }
internal static TokenCredential CreateCredential(IConfiguration configuration, TokenCredentialOptions identityClientOptions = null) { var credentialType = configuration["credential"]; var clientId = configuration["clientId"]; var tenantId = configuration["tenantId"]; var clientSecret = configuration["clientSecret"]; var certificate = configuration["clientCertificate"]; var certificateStoreName = configuration["clientCertificateStoreName"]; var certificateStoreLocation = configuration["clientCertificateStoreLocation"]; if (string.Equals(credentialType, "managedidentity", StringComparison.OrdinalIgnoreCase)) { return(new ManagedIdentityCredential(clientId)); } if (!string.IsNullOrWhiteSpace(tenantId) && !string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(clientSecret)) { return(new ClientSecretCredential(tenantId, clientId, clientSecret, identityClientOptions)); } if (!string.IsNullOrWhiteSpace(tenantId) && !string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(certificate)) { StoreLocation storeLocation = StoreLocation.CurrentUser; if (!string.IsNullOrWhiteSpace(certificateStoreLocation)) { storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), certificateStoreLocation, true); } if (string.IsNullOrWhiteSpace(certificateStoreName)) { certificateStoreName = "MY"; // MY is the default used in X509Store } using var store = new X509Store(certificateStoreName, storeLocation); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByThumbprint, certificate, false); if (certs.Count == 0) { throw new InvalidOperationException($"Unable to find a certificate with thumbprint '{certificate}'"); } var credential = new ClientCertificateCredential(tenantId, clientId, certs[0], identityClientOptions); store.Close(); return(credential); } // TODO: More logging return(null); }
public void CreateWithX509Certificate2() { string tenantId = "00000000-0000-0000-0000-00000000"; string clientId = "00000000-0000-0000-0000-00000000"; #region Snippet:Identity_CertificateCredenetial_CreateWithX509Cert var certificate = new X509Certificate2("./certs/cert-password-protected.pfx", "password"); var credential = new ClientCertificateCredential(tenantId, clientId, certificate); #endregion }
//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 ClientCertificateCredential certCredential; if (!ClientCertCredentialMap.TryGetValue(spParameters.ApplicationId, out certCredential)) { //first time login var certificate = AzureSession.Instance.DataStore.GetCertificate(spParameters.Thumbprint); certCredential = new ClientCertificateCredential(tenantId, spParameters.ApplicationId, certificate, options); var tokenTask = certCredential.GetTokenAsync(requestContext, cancellationToken); return(MsalAccessToken.GetAccessTokenAsync(tokenTask, () => { ClientCertCredentialMap[spParameters.ApplicationId] = certCredential; }, spParameters.TenantId, spParameters.ApplicationId)); } else { var tokenTask = certCredential.GetTokenAsync(requestContext, cancellationToken); return(MsalAccessToken.GetAccessTokenAsync(tokenTask, spParameters.TenantId, spParameters.ApplicationId)); } } else if (spParameters.Secret != null) { // service principal with secret var secretCredential = new ClientSecretCredential(tenantId, spParameters.ApplicationId, spParameters.Secret.ConvertToString(), options); var tokenTask = secretCredential.GetTokenAsync(requestContext, cancellationToken); return(MsalAccessToken.GetAccessTokenAsync( tokenTask, spParameters.TenantId, spParameters.ApplicationId)); } else { throw new MsalException(MsalError.AuthenticationFailed, string.Format(AuthenticationFailedMessage, clientId)); } }
//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), SendCertificateChain = spParameters.SendCertificateChain ?? default(bool) }; 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); var parametersLog = $"- Thumbprint:'{spParameters.Thumbprint}', ApplicationId:'{spParameters.ApplicationId}', TenantId:'{tenantId}', Scopes:'{string.Join(",", scopes)}', AuthorityHost:'{options.AuthorityHost}'"; return(MsalAccessToken.GetAccessTokenAsync( nameof(ServicePrincipalAuthenticator), parametersLog, 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); var parametersLog = $"- ApplicationId:'{spParameters.ApplicationId}', TenantId:'{tenantId}', Scopes:'{string.Join(",", scopes)}', AuthorityHost:'{options.AuthorityHost}'"; return(MsalAccessToken.GetAccessTokenAsync( nameof(ServicePrincipalAuthenticator), parametersLog, secretCredential, requestContext, cancellationToken, spParameters.TenantId, spParameters.ApplicationId)); } else { throw new MsalException(MsalError.AuthenticationFailed, string.Format(AuthenticationFailedMessage, clientId)); } }
public void RefreshCertificate() { lock (_refreshLock) { var certificateLastModified = File.GetLastWriteTimeUtc(_path); if (_credentialLastModified < certificateLastModified) { _credential = new ClientCertificateCredential(_tenantId, _clientId, new X509Certificate2(_path)); _credentialLastModified = certificateLastModified; } } }
public void IncorrectCertificate() { var tenantId = TestEnvironment.ServicePrincipalTenantId; var clientId = TestEnvironment.ServicePrincipalClientId; var certPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", "cert.pfx"); var options = InstrumentClientOptions(new TokenCredentialOptions()); var credential = new ClientCertificateCredential(tenantId, clientId, new X509Certificate2(certPath), options); var tokenRequestContext = new TokenRequestContext(new[] { AzureAuthorityHosts.GetDefaultScope(AzureAuthorityHosts.AzurePublicCloud) }); // ensure the incorrect client claim is rejected, handled and wrapped in AuthenticationFailedException Assert.ThrowsAsync <AuthenticationFailedException>(async() => await credential.GetTokenAsync(tokenRequestContext)); }
public void CreateFromStore() { string tenantId = "00000000-0000-0000-0000-00000000"; string clientId = "00000000-0000-0000-0000-00000000"; string thumbprint = ""; #region Snippet:Identity_CertificateCredenetial_CreateFromStore using var store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); var certificate = store.Certificates.Cast <X509Certificate2>().FirstOrDefault(cert => cert.Thumbprint == thumbprint); var credential = new ClientCertificateCredential(tenantId, clientId, certificate); #endregion }
public void VerifyClientCertificateCredentialException(bool usePemFile) { string expectedInnerExMessage = Guid.NewGuid().ToString(); var mockMsalClient = new MockMsalConfidentialClient(new MockClientException(expectedInnerExMessage)); var expectedTenantId = Guid.NewGuid().ToString(); var expectedClientId = Guid.NewGuid().ToString(); var certificatePath = Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", "cert.pfx"); var certificatePathPem = Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", "cert.pem"); var mockCert = new X509Certificate2(certificatePath); ClientCertificateCredential credential = InstrumentClient( usePemFile ? new ClientCertificateCredential(expectedTenantId, expectedClientId, certificatePathPem, default, default, mockMsalClient) : new ClientCertificateCredential(expectedTenantId, expectedClientId, mockCert, default, default, mockMsalClient)
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("Get Groups using Azure.Identity..."); #if DEBUG log.LogInformation("Using client credentials"); X509Certificate2 cert = Certs.GetCertificateFromStore(Configuration.LocalDevCertName); var credential = new ClientCertificateCredential(Configuration.LocalDevTenantId, Configuration.LocalDevAppId, cert); #else log.LogInformation("Using Managed identity credentials"); var credential = new ManagedIdentityCredential(); #endif try { var accessTokenRequest = await credential.GetTokenAsync( new TokenRequestContext(scopes : new string[] { "https://graph.microsoft.com/.default" }) { } ); var accessToken = accessTokenRequest.Token; //log.LogInformation(accessToken); var httpClient = new HttpClient() { DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", accessToken) } }; var result = await httpClient.GetStringAsync("https://graph.microsoft.com/v1.0/groups"); return(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(result, Encoding.UTF8, "application/json") }); } catch (AuthenticationFailedException ex) { log.LogError($"Authentication Failed. {ex.Message}"); return(null); } }
public async Task AuthnenticateWithAssertionCallback(bool useAsyncCallback) { var tenantId = TestEnvironment.ServicePrincipalTenantId; var clientId = TestEnvironment.ServicePrincipalClientId; var cert = new X509Certificate2(TestEnvironment.ServicePrincipalCertificatePfxPath); var options = InstrumentClientOptions(new ClientAssertionCredentialOptions()); ClientAssertionCredential credential; if (useAsyncCallback) { Func <CancellationToken, Task <string> > assertionCallback = (ct) => Task.FromResult(CreateClientAssertionJWT(options.AuthorityHost, clientId, tenantId, cert)); credential = InstrumentClient(new ClientAssertionCredential(tenantId, clientId, assertionCallback, options)); } else { Func <string> assertionCallback = () => CreateClientAssertionJWT(options.AuthorityHost, clientId, tenantId, cert); credential = InstrumentClient(new ClientAssertionCredential(tenantId, clientId, assertionCallback, options)); } var tokenRequestContext = new TokenRequestContext(new[] { AzureAuthorityHosts.GetDefaultScope(new Uri(TestEnvironment.AuthorityHostUrl)) }); // ensure we can initially acquire a token AccessToken token = await credential.GetTokenAsync(tokenRequestContext); Assert.IsNotNull(token.Token); // ensure subsequent calls before the token expires are served from the token cache AccessToken cachedToken = await credential.GetTokenAsync(tokenRequestContext); Assert.AreEqual(token.Token, cachedToken.Token); // ensure new credentials don't share tokens from the cache var credential2 = new ClientCertificateCredential(tenantId, clientId, cert, options); AccessToken token2 = await credential2.GetTokenAsync(tokenRequestContext); // this assert is conditional because the access token is scrubbed in the recording so they will never be different if (Mode != RecordedTestMode.Playback && Mode != RecordedTestMode.None) { Assert.AreNotEqual(token.Token, token2.Token); } }
public async Task IncludeX5CCliamHeader() { var tenantId = TestEnvironment.ServicePrincipalTenantId; var clientId = TestEnvironment.ServicePrincipalClientId; var certPath = TestEnvironment.ServicePrincipalSniCertificatePath; var options = InstrumentClientOptions(new ClientCertificateCredentialOptions { IncludeX5CCliamHeader = true }); var credential = new ClientCertificateCredential(tenantId, clientId, certPath, options); var tokenRequestContext = new TokenRequestContext(new[] { AzureAuthorityHosts.GetDefaultScope(AzureAuthorityHosts.AzurePublicCloud) }); // ensure we can initially acquire a token AccessToken token = await credential.GetTokenAsync(tokenRequestContext); Assert.IsNotNull(token.Token); }
private static async Task GetClientSecretCredentialCredentialWithCertificate() { 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"); X509Certificate2 x509Certificate2 = new X509Certificate2("mycert.pfx", "Nemore11"); ClientCertificateCredential clientCertificateCredential = new ClientCertificateCredential("9cacb64e-358b-418b-967a-3cabc2a0ea95", "317bd2d8-58b7-4be6-b5bc-d5567a6df8db", x509Certificate2); TokenCredentialAuthProvider tokenCredentialAuthProvider = new TokenCredentialAuthProvider(clientCertificateCredential, 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); }
public void VerifyBadCertificateFileBehavior() { var tenantId = Guid.NewGuid().ToString(); var clientId = Guid.NewGuid().ToString(); TokenRequestContext tokenContext = new TokenRequestContext(MockScopes.Default); ClientCertificateCredential missingFileCredential = new ClientCertificateCredential(tenantId, clientId, Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", "notfound.pem")); ClientCertificateCredential invalidPemCredential = new ClientCertificateCredential(tenantId, clientId, Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", "cert-invalid-data.pem")); ClientCertificateCredential unknownFormatCredential = new ClientCertificateCredential(tenantId, clientId, Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", "cert.unknown")); ClientCertificateCredential encryptedCredential = new ClientCertificateCredential(tenantId, clientId, Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", "cert.pfx")); Assert.Throws <CredentialUnavailableException>(() => missingFileCredential.GetToken(tokenContext)); Assert.Throws <CredentialUnavailableException>(() => invalidPemCredential.GetToken(tokenContext)); Assert.Throws <CredentialUnavailableException>(() => unknownFormatCredential.GetToken(tokenContext)); Assert.Throws <CredentialUnavailableException>(() => encryptedCredential.GetToken(tokenContext)); Assert.ThrowsAsync <CredentialUnavailableException>(async() => await missingFileCredential.GetTokenAsync(tokenContext)); Assert.ThrowsAsync <CredentialUnavailableException>(async() => await invalidPemCredential.GetTokenAsync(tokenContext)); Assert.ThrowsAsync <CredentialUnavailableException>(async() => await unknownFormatCredential.GetTokenAsync(tokenContext)); Assert.ThrowsAsync <CredentialUnavailableException>(async() => await encryptedCredential.GetTokenAsync(tokenContext)); }
private static void AddUserSecrets(HostBuilderContext ctx, IConfigurationBuilder builder) { if (ctx.HostingEnvironment.IsDevelopment()) { builder.AddUserSecrets <Program>(); } else { var root = builder.Build(); var vaultName = root["KeyVault:Name"]; var appId = root["KeyVault:ADApplicationId"]; var directoryId = root["KeyVault:ADDirectoryId"]; var cert = GetApplicationCertificate(root); var uri = new Uri($"https://{vaultName}.vault.azure.net/"); var credential = new ClientCertificateCredential(directoryId, appId, cert); var manager = new KeyVaultSecretManager(); builder.AddAzureKeyVault(uri, credential, manager); } }
static void Main(string[] args) { Console.WriteLine("Message sender"); var cert = GetCert("sugarsus-sender1"); var cred = new ClientCertificateCredential(_tenantId, _clientId, cert); var queue = new QueueClient(new Uri(_queueUri), cred); var count = 0; Console.WriteLine("Press any key to send message or 'x' to stop."); var key = Console.ReadKey(); while (key.KeyChar != 'x') { var resp = queue.EnqueueMessage($"{count}. Test {DateTime.Now}"); ++count; key = Console.ReadKey(); } Console.WriteLine(); Console.WriteLine($"Sent {count} message(s)."); Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine("Message reader"); var count = 0; var cert = GetCert("sugarsus-receiver"); var cred = new ClientCertificateCredential(_tenantId, _clientId, cert); var queue = new QueueClient(new Uri(_queueUri), cred); while (true) { try { var resp = queue.DequeueMessages(); foreach (var msg in resp.Value) { if (msg.DequeueCount > 3) { Console.WriteLine("Bad msg. Moving to dead letter queue"); // move the message to somewhere else where you can investigate it } else { Console.WriteLine($"Processing: {msg.MessageText}"); } ++count; queue.DeleteMessage(msg.MessageId, msg.PopReceipt); } } catch (StorageRequestFailedException ex) { Console.WriteLine(""); break; } } Console.WriteLine($"Processed {count} message(s)."); Console.ReadLine(); }
public void RotateCertificate(X509Certificate2 certificate) { _credential = new ClientCertificateCredential(_tenantId, _clientId, certificate); }