/// <summary> /// Creates a public client used for generating tokens. /// </summary> /// <param name="cloudInstance">The cloud instance used for authentication.</param> /// <param name="clientId">Identifier of the client requesting the token.</param> /// <param name="redirectUri">The redirect URI for the client.</param> /// <param name="tenantId">Identifier of the tenant requesting the token.</param> /// <returns>An aptly configured public client.</returns> private static IPublicClientApplication CreatePublicClient( AzureCloudInstance cloudInstance, string clientId = null, string redirectUri = null, string tenantId = null) { PublicClientApplicationBuilder builder = PublicClientApplicationBuilder.Create(clientId); builder = builder.WithAuthority(cloudInstance, tenantId); if (!string.IsNullOrEmpty(redirectUri)) { builder = builder.WithRedirectUri(redirectUri); } if (!string.IsNullOrEmpty(tenantId)) { builder = builder.WithTenantId(tenantId); } IPublicClientApplication client = builder.WithLogging((level, message, pii) => { MgmtSession.Instance.DebugMessages.Enqueue($"[MSAL] {level} {message}"); }).Build(); if (MgmtSession.Instance.TryGetComponent(ComponentKey.TokenCache, out IMgmtTokenCache tokenCache)) { ServiceClientTracing.Information($"[MSAL] Registering the token cache for client {clientId}"); tokenCache.RegisterCache(client); } return(client); }
/// <summary> /// Creates a public client used for generating tokens. /// </summary> /// <param name="cloudInstance">The cloud instance used for authentication.</param> /// <param name="clientId">Identifier of the client requesting the token.</param> /// <param name="redirectUri">The redirect URI for the client.</param> /// <param name="tenantId">Identifier of the tenant requesting the token.</param> /// <returns>An aptly configured public client.</returns> private static IPublicClientApplication CreatePublicClient( AzureCloudInstance cloudInstance, string clientId = null, string redirectUri = null, string tenantId = null) { PublicClientApplicationBuilder builder = PublicClientApplicationBuilder.Create(clientId); builder = builder.WithAuthority(cloudInstance, tenantId); if (!string.IsNullOrEmpty(redirectUri)) { builder = builder.WithRedirectUri(redirectUri); } if (!string.IsNullOrEmpty(tenantId)) { builder = builder.WithTenantId(tenantId); } IPublicClientApplication client = builder.WithLogging((level, message, pii) => { PartnerSession.Instance.DebugMessages.Enqueue($"[MSAL] {level} {message}"); }).Build(); return(client); }
/// <summary> /// Adds a known Azure AD authority to the application to sign-in users specifying /// the cloud instance and the sign-in audience. See https://aka.ms/msal-net-application-configuration. /// </summary> /// <param name="azureCloudInstance">Instance of Azure Cloud (for instance Azure /// worldwide cloud, Azure German Cloud, US government ...)</param> /// <param name="authorityAudience">Sign-in audience (one AAD organization, /// any work and school accounts, or any work and school accounts and Microsoft personal /// accounts</param> /// <param name="validateAuthority">Whether the authority should be validated against the server metadata.</param> /// <returns>The builder to chain the .With methods</returns> public T WithAuthority(AzureCloudInstance azureCloudInstance, AadAuthorityAudience authorityAudience, bool validateAuthority = true) { Config.AzureCloudInstance = azureCloudInstance; Config.AadAuthorityAudience = authorityAudience; Config.ValidateAuthority = validateAuthority; return((T)this); }
/// <summary> /// Adds a known Azure AD authority to the application to sign-in users from a single /// organization (single tenant application) described by its cloud instance and its domain /// name or tenant ID. See https://aka.ms/msal-net-application-configuration. /// </summary> /// <param name="azureCloudInstance">Instance of Azure Cloud (for instance Azure /// worldwide cloud, Azure German Cloud, US government ...)</param> /// <param name="tenant">Domain name associated with the Azure AD tenant from which /// <param name="validateAuthority">Whether the authority should be validated against the server metadata.</param> /// to sign-in users. This can also be a guid</param> /// <returns>The builder to chain the .With methods</returns> public T WithAuthority( AzureCloudInstance azureCloudInstance, string tenant, bool validateAuthority = true) { Config.AuthorityInfo = AuthorityInfo.FromAadAuthority(azureCloudInstance, tenant, validateAuthority); return((T)this); }
/// <summary> /// Adds a known Azure AD authority to the application to sign-in users from a single /// organization (single tenant application) described by its cloud instance and its domain /// name or tenant ID. See https://aka.ms/msal-net-application-configuration. /// </summary> /// <param name="azureCloudInstance">Instance of Azure Cloud (for instance Azure /// worldwide cloud, Azure German Cloud, US government ...).</param> /// <param name="tenant">Tenant Id of the tenant from which to sign-in users. This can also be a GUID.</param> /// <param name="validateAuthority">Whether the authority should be validated against the server metadata.</param> /// <returns>The builder to chain the .With methods.</returns> public T WithAuthority( AzureCloudInstance azureCloudInstance, string tenant, bool validateAuthority = true) { CommonParameters.AuthorityOverride = AuthorityInfo.FromAadAuthority(azureCloudInstance, tenant, validateAuthority); return((T)this); }
protected void ValidateAzureTenantConnection() { if (String.IsNullOrWhiteSpace(this.TxtTenantName.Text) || String.IsNullOrWhiteSpace(this.TxtClientId.Text)) { this.LabelErrorTestLdapConnection.Text = TextErrorNewTenantFieldsMissing; return; } if ((InputClientCertFile.PostedFile == null && String.IsNullOrWhiteSpace(this.TxtClientSecret.Text)) || (InputClientCertFile.PostedFile != null && InputClientCertFile.PostedFile.ContentLength == 0 && String.IsNullOrWhiteSpace(TxtClientSecret.Text)) || (InputClientCertFile.PostedFile != null && InputClientCertFile.PostedFile.ContentLength != 0 && !String.IsNullOrWhiteSpace(TxtClientSecret.Text))) { this.LabelErrorTestLdapConnection.Text = TextErrorNewTenantCreds; return; } string tenantName = this.TxtTenantName.Text; string clientId = this.TxtClientId.Text; string clientSecret = this.TxtClientSecret.Text; AzureCloudInstance cloudInstance = (AzureCloudInstance)Enum.Parse(typeof(AzureCloudInstance), this.DDLAzureCloudInstance.SelectedValue); // The whole flow of setting the certificate and testing it in AADAppOnlyAuthenticationProvider needs to be done as app pool account // Otherwise AADAppOnlyAuthenticationProvider throws CryptographicException: Keyset does not exist (which means it could not access the private key) SPSecurity.RunWithElevatedPrivileges(delegate() { X509Certificate2 cert = null; if (String.IsNullOrWhiteSpace(this.TxtClientSecret.Text)) { if (ValidateUploadedCertFile(InputClientCertFile, this.InputClientCertPassword.Text, out cert) == false) { return; } } try { AADAppOnlyAuthenticationProvider testConnection; if (String.IsNullOrWhiteSpace(this.TxtClientSecret.Text)) { testConnection = new AADAppOnlyAuthenticationProvider(cloudInstance, tenantName, clientId, cert, String.Empty, ClaimsProviderConstants.DEFAULT_TIMEOUT); } else { testConnection = new AADAppOnlyAuthenticationProvider(cloudInstance, tenantName, clientId, clientSecret, String.Empty, ClaimsProviderConstants.DEFAULT_TIMEOUT); } Task <bool> testConnectionTask = testConnection.GetAccessToken(true); testConnectionTask.Wait(); this.LabelTestTenantConnectionOK.Text = TextConnectionSuccessful; } catch (MsalServiceException ex) { this.LabelErrorTestLdapConnection.Text = String.Format(TextErrorTestAzureADConnection, tenantName, ex.Message); } catch (Exception ex) { this.LabelErrorTestLdapConnection.Text = String.Format(TextErrorTestAzureADConnection, tenantName, ex.Message); } }); }
internal static AuthorityInfo FromAadAuthority( AzureCloudInstance azureCloudInstance, AadAuthorityAudience authorityAudience, bool validateAuthority) { string authorityUri = GetAuthorityUri(azureCloudInstance, authorityAudience); return(new AuthorityInfo(AuthorityType.Aad, authorityUri, validateAuthority)); }
/// <summary> /// Configure the credentials for a user-created Kusto client /// </summary> /// <param name="tenantId">The tenant (directory) ID of the Azure AD application registration</param> /// <param name="clientId">The client ID of the application</param> /// <param name="secret">The client secret of the application</param> /// <param name="clusterName">Kusto/ADX cluster name</param> /// <param name="databaseName">Kusto database name</param> /// <param name="infoTable">Table for storing informational logs</param> /// <param name="warningTable">Table for storing warning logs</param> /// <param name="errorTable">Table for storing error logs</param> /// <param name="ingestAtLevel">Kusto ingestion security level for the execution environment</param> /// <param name="region">(Optional) Geographic information, e.g. "West US"</param> /// <param name="cloudInstance">(Optional) Azure cloud instance, default to be public cloud</param> /// <param name="removeUserContent">(Optional) Whether to remove all potential user created content</param> /// <remarks> /// The TelemetryKustoClient is designed to ingest into tables with the following schema: /// (timestamp: datetime, className: string, method: string, message: string, code: string, corpusPath: string, correlationId: string, apiCorrelationId: string, appId: string, property: string) /// Using a different schema may result in ingestion failure and missing data /// </remarks> public TelemetryConfig(string tenantId, string clientId, string secret, string clusterName, string databaseName, string infoTable, string warningTable, string errorTable, EnvironmentType ingestAtLevel, string region = null, AzureCloudInstance cloudInstance = AzureCloudInstance.AzurePublic, bool removeUserContent = true) : this(tenantId, clientId, secret, clusterName, databaseName, ingestAtLevel, region, cloudInstance, removeUserContent) { this.KustoInfoLogTable = infoTable; this.KustoWarningLogTable = warningTable; this.KustoErrorLogTable = errorTable; }
internal static string GetAuthorityUri( AzureCloudInstance azureCloudInstance, AadAuthorityAudience authorityAudience, string tenantId = null) { string cloudUrl = GetCloudUrl(azureCloudInstance); string tenantValue = GetAadAuthorityAudienceValue(authorityAudience, tenantId); return(string.Format(CultureInfo.InvariantCulture, "{0}/{1}", cloudUrl, tenantValue)); }
internal static AuthorityInfo FromAadAuthority( AzureCloudInstance azureCloudInstance, Guid tenantId, bool validateAuthority) { #pragma warning disable CA1305 // Specify IFormatProvider string authorityUri = GetAuthorityUri(azureCloudInstance, AadAuthorityAudience.AzureAdMyOrg, tenantId.ToString("D")); #pragma warning restore CA1305 // Specify IFormatProvider return(new AuthorityInfo(AuthorityType.Aad, authorityUri, validateAuthority)); }
/// <summary> /// Adds a known Azure AD authority to the application to sign-in users from a single /// organization (single tenant application) described by its cloud instance and its tenant ID. /// See https://aka.ms/msal-net-application-configuration. /// </summary> /// <param name="azureCloudInstance">Instance of Azure Cloud (for instance Azure /// worldwide cloud, Azure German Cloud, US government ...)</param> /// <param name="tenantId">Tenant Id of the tenant from which to sign-in users</param> /// <param name="validateAuthority">Whether the authority should be validated against the server metadata.</param> /// <returns>The builder to chain the .With methods</returns> public T WithAuthority( AzureCloudInstance azureCloudInstance, Guid tenantId, bool validateAuthority = true) { #pragma warning disable CA1305 // Specify IFormatProvider - this overload is missing on netstandard WithAuthority(azureCloudInstance, tenantId.ToString("D"), validateAuthority); #pragma warning restore CA1305 // Specify IFormatProvider return((T)this); }
/// <summary> /// Adds a known Azure AD authority to the application to sign-in users specifying /// the cloud instance and the sign-in audience. See https://aka.ms/msal-net-application-configuration. /// </summary> /// <param name="azureCloudInstance">Instance of Azure Cloud (for instance Azure /// worldwide cloud, Azure German Cloud, US government ...).</param> /// <param name="authorityAudience">Sign-in audience (one AAD organization, /// any work and school accounts, or any work and school accounts and Microsoft personal /// accounts.</param> /// <param name="validateAuthority">Whether the authority should be validated against the server metadata.</param> /// <returns>The builder to chain the .With methods.</returns> public T WithAuthority(AzureCloudInstance azureCloudInstance, AadAuthorityAudience authorityAudience, bool validateAuthority = true) { CommonParameters.AddApiTelemetryFeature(ApiTelemetryFeature.WithAuthority); if (validateAuthority) { CommonParameters.AddApiTelemetryFeature(ApiTelemetryFeature.WithValidateAuthority); } CommonParameters.AuthorityOverride = AuthorityInfo.FromAadAuthority(azureCloudInstance, authorityAudience, validateAuthority); return((T)this); }
private PublicClientApplication InitPcaFromCacheFile( AzureCloudInstance cloud, HttpManager httpManager, string tokenCacheFile) { return(InitPcaFromCacheString( cloud, httpManager, File.ReadAllText( ResourceHelper.GetTestResourceRelativePath(tokenCacheFile)))); }
/// <summary> /// Configure the credentials for the default log table names /// with the credentials of the AAD app that has been granted permission in the CDM Kusto cluster /// </summary> /// <param name="tenantId">The tenant (directory) ID of the Azure AD application registration</param> /// <param name="clientId">The client ID of the application</param> /// <param name="secret">The client secret of the application</param> /// <param name="clusterName">Kusto/ADX cluster name</param> /// <param name="databaseName">Kusto database name</param> /// <param name="ingestAtLevel">Kusto ingestion security level for the execution environment</param> /// <param name="region">(Optional) Geographic information, e.g. "West US"</param> /// <param name="cloudInstance">(Optional) Azure cloud instance, default to be public cloud</param> /// <param name="removeUserContent">(Optional) Whether to remove all potential user created content</param> /// <remarks> /// The TelemetryKustoClient is designed to ingest into tables with the following schema: /// (timestamp: datetime, className: string, method: string, message: string, code: string, corpusPath: string, correlationId: string, apiCorrelationId: string, appId: string, property: string) /// Using a different schema may result in ingestion failure and missing data /// </remarks> public TelemetryConfig(string tenantId, string clientId, string secret, string clusterName, string databaseName, EnvironmentType ingestAtLevel, string region = null, AzureCloudInstance cloudInstance = AzureCloudInstance.AzurePublic, bool removeUserContent = true) : this(ingestAtLevel, region, removeUserContent) { this.TenantId = tenantId; this.ClientId = clientId; this.Secret = secret; this.KustoClusterName = clusterName; this.KustoDatabaseName = databaseName; this.CloudInstance = cloudInstance; }
private PublicClientApplication InitPcaForCloud(AzureCloudInstance cloud, HttpManager httpManager, string tokenCacheFile) { PublicClientApplication pca = PublicClientApplicationBuilder .Create(ClientIdInFile) .WithAuthority(cloud, AadAuthorityAudience.PersonalMicrosoftAccount) .WithHttpManager(httpManager) .BuildConcrete(); pca.InitializeTokenCacheFromFile(ResourceHelper.GetTestResourceRelativePath(tokenCacheFile)); pca.UserTokenCacheInternal.Accessor.AssertItemCount(3, 3, 3, 3, 1); return(pca); }
internal static AuthorityInfo FromAadAuthority( AzureCloudInstance azureCloudInstance, string tenant, bool validateAuthority) { if (Guid.TryParse(tenant, out Guid tenantIdGuid)) { return(FromAadAuthority(azureCloudInstance, tenantIdGuid, validateAuthority)); } string authorityUri = GetAuthorityUri(azureCloudInstance, AadAuthorityAudience.AzureAdMyOrg, tenant); return(new AuthorityInfo(AuthorityType.Aad, authorityUri, validateAuthority)); }
protected override ValueTask <AuthenticationResult> AcquireTokenByRefreshTokenCoreAsync( string[] scopes, string claims, string refreshToken, AzureCloudInstance azureCloudInstance, string tenant, bool async, CancellationToken cancellationToken) { if (RefreshTokenFactory == null) { throw new NotImplementedException(); } return(new ValueTask <AuthenticationResult>(RefreshTokenFactory(scopes, claims, refreshToken, azureCloudInstance, tenant, async, cancellationToken))); }
/// <summary> /// Adds a known Azure AD authority to the application to sign-in users from a single /// organization (single tenant application) described by its cloud instance and its domain /// name or tenant ID. See https://aka.ms/msal-net-application-configuration. /// </summary> /// <param name="azureCloudInstance">Instance of Azure Cloud (for instance Azure /// worldwide cloud, Azure German Cloud, US government ...)</param> /// <param name="tenant">Domain name associated with the Azure AD tenant from which /// <param name="validateAuthority">Whether the authority should be validated against the server metadata.</param> /// to sign-in users. This can also be a guid</param> /// <returns>The builder to chain the .With methods</returns> public T WithAuthority( AzureCloudInstance azureCloudInstance, string tenant, bool validateAuthority = true) { if (string.IsNullOrWhiteSpace(tenant)) { throw new ArgumentNullException(nameof(tenant)); } Config.AzureCloudInstance = azureCloudInstance; Config.TenantId = tenant; Config.ValidateAuthority = validateAuthority; return((T)this); }
public void TestAuthorityPermutations( AzureCloudInstance cloudInstance, AadAuthorityAudience audience, string expectedAuthority) { var options = new PublicClientApplicationOptions { AzureCloudInstance = cloudInstance, AadAuthorityAudience = audience, ClientId = TestConstants.ClientId }; var pca = PublicClientApplicationBuilder.CreateWithApplicationOptions(options) .Build(); Assert.AreEqual(expectedAuthority, pca.Authority); }
public static string GetAuthorityUrl(this AzureCloudInstance azureCloudInstance, AadAuthorityAudience authorityAudience = default(AadAuthorityAudience), string tenantId = null) { return(String.Format(CultureInfo.InvariantCulture, "{0}/{1}/", GetCloudUri(), GetAudienceUri())); string GetAudienceUri() { return((authorityAudience, tenantId) switch { (AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount, _) => "common", (AadAuthorityAudience.AzureAdMultipleOrgs, _) => "organizations", (AadAuthorityAudience.PersonalMicrosoftAccount, _) => "consumers", (AadAuthorityAudience.AzureAdMyOrg, _)when !String.IsNullOrWhiteSpace(tenantId) => tenantId, (AadAuthorityAudience.AzureAdMyOrg, _) when String.IsNullOrWhiteSpace(tenantId) => throw new ArgumentException(nameof(tenantId)), (_, _) => throw new ArgumentException(nameof(authorityAudience)) }); }
private PublicClientApplication InitPcaFromCacheString( AzureCloudInstance cloud, HttpManager httpManager, string tokenCacheString) { PublicClientApplication pca = PublicClientApplicationBuilder .Create(ClientIdInFile) .WithAuthority(cloud, AadAuthorityAudience.PersonalMicrosoftAccount) .WithHttpManager(httpManager) .WithTelemetry(new TraceTelemetryConfig()) .BuildConcrete(); pca.InitializeTokenCacheFromString(tokenCacheString); pca.UserTokenCacheInternal.Accessor.AssertItemCount(3, 3, 3, 3, 1); return(pca); }
/// <summary> /// Creates a confidential client used for generating tokens. /// </summary> /// <param name="cloudInstance">The cloud instance used for authentication.</param> /// <param name="clientId">Identifier of the client requesting the token.</param> /// <param name="certificate">Certificate used by the client requesting the token.</param> /// <param name="clientSecret">Secret of the client requesting the token.</param> /// <param name="redirectUri">The redirect URI for the client.</param> /// <param name="tenantId">Identifier of the tenant requesting the token.</param> /// <returns>An aptly configured confidential client.</returns> private static IConfidentialClientApplication CreateConfidentialClient( AzureCloudInstance cloudInstance, string clientId = null, string clientSecret = null, X509Certificate2 certificate = null, string redirectUri = null, string tenantId = null) { ConfidentialClientApplicationBuilder builder = ConfidentialClientApplicationBuilder.Create(clientId); builder = builder.WithAuthority(cloudInstance, tenantId); if (!string.IsNullOrEmpty(clientSecret)) { builder = builder.WithClientSecret(clientSecret); } if (certificate != null) { builder = builder.WithCertificate(certificate); } if (!string.IsNullOrEmpty(redirectUri)) { builder = builder.WithRedirectUri(redirectUri); } if (!string.IsNullOrEmpty(tenantId)) { builder = builder.WithTenantId(tenantId); } IConfidentialClientApplication client = builder.WithLogging((level, message, pii) => { PartnerSession.Instance.DebugMessages.Enqueue($"[MSAL] {level} {message}"); }).Build(); if (PartnerSession.Instance.TryGetComponent(ComponentKey.TokenCache, out IPartnerTokenCache tokenCache)) { tokenCache.RegisterCache(client); } return(client); }
public AADAppOnlyAuthenticationProvider(AzureCloudInstance cloudInstance, string tenant, string clientId, X509Certificate2 ClientCertificate, string claimsProviderName, int timeout) { this.ClientCertificate = ClientCertificate; this.Tenant = tenant; this.ClientId = clientId; this.ClaimsProviderName = claimsProviderName; this.Timeout = timeout; this.CloudInstance = cloudInstance; this.GraphServiceEndpoint = ClaimsProviderConstants.AzureCloudEndpoints.SingleOrDefault(kvp => kvp.Key == cloudInstance).Value; UriBuilder scopeBuilder = new UriBuilder(this.GraphServiceEndpoint); scopeBuilder.Path = "/.default"; this.Scopes = new List <string>(1) { scopeBuilder.Uri.ToString() }; }
internal static string GetCloudUrl(AzureCloudInstance azureCloudInstance) { switch (azureCloudInstance) { case AzureCloudInstance.AzurePublic: return("https://login.microsoftonline.com"); case AzureCloudInstance.AzureChina: return("https://login.chinacloudapi.cn"); case AzureCloudInstance.AzureGermany: return("https://login.microsoftonline.de"); case AzureCloudInstance.AzureUsGovernment: return("https://login.microsoftonline.us"); default: throw new ArgumentException(nameof(azureCloudInstance)); } }
public virtual async ValueTask <AuthenticationResult> AcquireTokenByRefreshToken(string[] scopes, string claims, string refreshToken, AzureCloudInstance azureCloudInstance, string tenant, bool async, CancellationToken cancellationToken) { IPublicClientApplication client = await GetClientAsync(async, cancellationToken).ConfigureAwait(false); return(await((IByRefreshToken)client).AcquireTokenByRefreshToken(scopes, refreshToken) .WithAuthority(azureCloudInstance, tenant) .WithClaims(claims) .ExecuteAsync(async, cancellationToken) .ConfigureAwait(false)); }
/// <summary> /// Adds a known Azure AD authority to the application to sign-in users specifying /// the cloud instance and the sign-in audience. See https://aka.ms/msal-net-application-configuration. /// </summary> /// <param name="azureCloudInstance">Instance of Azure Cloud (for instance Azure /// worldwide cloud, Azure German Cloud, US government ...)</param> /// <param name="authorityAudience">Sign-in audience (one AAD organization, /// any work and school accounts, or any work and school accounts and Microsoft personal /// accounts</param> /// <param name="validateAuthority">Whether the authority should be validated against the server metadata.</param> /// <returns>The builder to chain the .With methods</returns> public T WithAuthority(AzureCloudInstance azureCloudInstance, AadAuthorityAudience authorityAudience, bool validateAuthority = true) { Config.AuthorityInfo = AuthorityInfo.FromAadAuthority(azureCloudInstance, authorityAudience, validateAuthority); return((T)this); }
public virtual async Task <AuthenticationResult> AcquireTokenByRefreshToken(string[] scopes, string refreshToken, AzureCloudInstance azureCloudInstance, string tenant, bool async, CancellationToken cancellationToken) { return(await((IByRefreshToken)_client).AcquireTokenByRefreshToken(scopes, refreshToken).WithAuthority(azureCloudInstance, tenant).ExecuteAsync(async, cancellationToken).ConfigureAwait(false)); }
public async ValueTask <AuthenticationResult> AcquireTokenByRefreshTokenAsync(string[] scopes, string claims, string refreshToken, AzureCloudInstance azureCloudInstance, string tenant, bool async, CancellationToken cancellationToken) { return(await AcquireTokenByRefreshTokenCoreAsync(scopes, claims, refreshToken, azureCloudInstance, tenant, async, cancellationToken).ConfigureAwait(false)); }