public void CacheSynchronizationWithDefault() { var options = new ConfidentialClientApplicationOptions() { ClientSecret = "secret", ClientId = TestConstants.ClientId, }; var app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options).Build(); Assert.IsTrue((app.AppConfig as ApplicationConfiguration).CacheSynchronizationEnabled); options = new ConfidentialClientApplicationOptions { ClientId = TestConstants.ClientId, ClientSecret = "secret", EnableCacheSynchronization = false }; app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options).Build(); Assert.AreEqual(false, (app.AppConfig as ApplicationConfiguration).CacheSynchronizationEnabled); options = new ConfidentialClientApplicationOptions { ClientId = TestConstants.ClientId, ClientSecret = "secret", EnableCacheSynchronization = true }; app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options).Build(); Assert.AreEqual(true, (app.AppConfig as ApplicationConfiguration).CacheSynchronizationEnabled); }
private IConfidentialClientApplication GetOrCreateApplication() { if (_application == null) { lock (_applicationSyncObj) { if (_application == null) { var options = new ConfidentialClientApplicationOptions() { ClientId = AppServicesAuthenticationInformation.ClientId, ClientSecret = AppServicesAuthenticationInformation.ClientSecret, Instance = AppServicesAuthenticationInformation.Issuer, }; _application = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options) .WithHttpClientFactory(_httpClientFactory) .Build(); _tokenCacheProvider.Initialize(_application.AppTokenCache); _tokenCacheProvider.Initialize(_application.UserTokenCache); } } } return(_application); }
/// <summary> /// Creates an MSAL Confidential client application /// </summary> /// <param name="httpContext"></param> /// <param name="claimsPrincipal"></param> /// <returns></returns> private IConfidentialClientApplication BuildConfidentialClientApplication( HttpContext httpContext, ClaimsPrincipal claimsPrincipal) { var request = httpContext.Request; string currentUri = UriHelper.BuildAbsolute( request.Scheme, request.Host, request.PathBase, _azureAdOptions.CallbackPath ?? string.Empty); string authority = $"{_azureAdOptions.Instance}{_azureAdOptions.TenantId}/"; var app = ConfidentialClientApplicationBuilder .CreateWithApplicationOptions(_applicationOptions) .WithRedirectUri(currentUri) .WithAuthority(authority) .Build(); // Initialize token cache providers if (_appTokenCacheProvider != null) { _appTokenCacheProvider.Initialize(app.AppTokenCache, httpContext); } if (_userTokenCacheProvider != null) { _userTokenCacheProvider.Initialize(app.UserTokenCache, httpContext, claimsPrincipal); } return(app); }
/// <summary> /// Creates an MSAL Confidential client application /// </summary> /// <param name="claimsPrincipal"></param> /// <returns></returns> private IConfidentialClientApplication BuildConfidentialClientApplication() { var request = CurrentHttpContext.Request; var azureAdOptions = _azureAdOptions; var applicationOptions = _applicationOptions; string currentUri = UriHelper.BuildAbsolute( request.Scheme, request.Host, request.PathBase, azureAdOptions.CallbackPath ?? string.Empty); string authority = $"{applicationOptions.Instance}{applicationOptions.TenantId}/"; var app = ConfidentialClientApplicationBuilder .CreateWithApplicationOptions(applicationOptions) .WithRedirectUri(currentUri) .WithAuthority(authority) .Build(); // Initialize token cache providers _tokenCacheProvider?.InitializeAsync(app.AppTokenCache); _tokenCacheProvider?.InitializeAsync(app.UserTokenCache); return(app); }
public void VerifyCorrectAuthorityUsedInTokenAcquisitionTests(string tenant) { _microsoftIdentityOptions = new MicrosoftIdentityOptions { Authority = TestConstants.AuthorityCommonTenant, ClientId = TestConstants.ConfidentialClientId, CallbackPath = string.Empty, }; BuildTheRequiredServices(); InitializeTokenAcquisitionObjects(); IConfidentialClientApplication app = ConfidentialClientApplicationBuilder .CreateWithApplicationOptions(_applicationOptions) .WithAuthority(TestConstants.AuthorityCommonTenant).Build(); if (!string.IsNullOrEmpty(tenant)) { Assert.Equal( string.Format( CultureInfo.InvariantCulture, "{0}/{1}/", TestConstants.AadInstance, tenant), _tokenAcquisition.CreateAuthorityBasedOnTenantIfProvided( app, tenant)); } else { Assert.Equal(app.Authority, _tokenAcquisition.CreateAuthorityBasedOnTenantIfProvided(app, tenant)); } }
/// <summary> /// Creates an MSAL Confidential client application. /// </summary> private async Task <IConfidentialClientApplication> BuildConfidentialClientApplicationAsync() { if (!_applicationOptions.Instance.EndsWith("/", StringComparison.InvariantCulture)) { _applicationOptions.Instance += "/"; } string authority; IConfidentialClientApplication app; MicrosoftIdentityOptionsValidation microsoftIdentityOptionsValidation = new MicrosoftIdentityOptionsValidation(); if (microsoftIdentityOptionsValidation.ValidateClientSecret(_applicationOptions).Failed) { string msg = string.Format(CultureInfo.InvariantCulture, "Client secret cannot be null or whitespace, " + "and must be included in the configuration of the web app when calling a web API. " + "For instance, in the appsettings.json file. "); _logger.LogInformation(msg); throw new MsalClientException( "missing_client_credentials", msg); } try { var builder = ConfidentialClientApplicationBuilder .CreateWithApplicationOptions(_applicationOptions) .WithRedirectUri(CreateRedirectUri()) .WithHttpClientFactory(_httpClientFactory); if (_microsoftIdentityOptions.IsB2C) { authority = $"{ _applicationOptions.Instance}tfp/{_microsoftIdentityOptions.Domain}/{_microsoftIdentityOptions.DefaultUserFlow}"; builder.WithB2CAuthority(authority); app = builder.Build(); } else { authority = $"{ _applicationOptions.Instance}{_applicationOptions.TenantId}/"; builder.WithAuthority(authority); app = builder.Build(); } // Initialize token cache providers await _tokenCacheProvider.InitializeAsync(app.AppTokenCache).ConfigureAwait(false); await _tokenCacheProvider.InitializeAsync(app.UserTokenCache).ConfigureAwait(false); return(app); } catch (Exception ex) { _logger.LogInformation( ex, string.Format(CultureInfo.InvariantCulture, "Exception acquiring token for a confidential client. ")); throw; } }
private void TestBuildConfidentialClientFromOptions(ConfidentialClientApplicationOptions options) { var app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options).Build(); var authorityInfo = ((ConfidentialClientApplication)app).ServiceBundle.Config.AuthorityInfo; Assert.AreEqual("https://login.microsoftonline.com/the_tenant_id/", authorityInfo.CanonicalAuthority); }
private IConfidentialClientApplication BuildConfidentialClientApplication() { //use MSAL for v2.0 //https://docs.microsoft.com/bs-latn-ba/azure/active-directory/develop/msal-net-instantiate-confidential-client-config-options //https://joonasw.net/view/azure-ad-v2-and-msal-from-dev-pov //https://securecloud.blog/2019/05/22/azure-api-management-jwt-validation-for-multiple-azure-ad-partner-registrations/ //https://thomaslevesque.com/2018/12/24/multitenant-azure-ad-issuer-validation-in-asp-net-core/ //https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-convert-app-to-be-multi-tenant var request = _httpContext.HttpContext.Request; var currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path); var co = new ConfidentialClientApplicationOptions { Instance = "https://login.microsoftonline.com/", TenantId = "common", ClientId = "b021b14e-1671-4fe6-b7cc-0a67a248543f", ClientSecret = "Ushs_5=SuttP50l7ZEovc?l]1[H3Z9k1", RedirectUri = currentUri }; var app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(co) .Build(); _cache.ConfigureCache(app); return(app); }
public async Task <TokenTenant> GetGraphToken(string domain) { try { var tenantId = await GetTenantId(domain); var daemonClient = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(new ConfidentialClientApplicationOptions() { ClientId = bottySettings.AppId, ClientSecret = bottySettings.AppSecrets, TenantId = tenantId, RedirectUri = bottySettings.Url }).Build(); var authResult = await daemonClient.AcquireTokenForClient(new string[] { msGraphScope }).ExecuteAsync(); var token = new TokenTenant() { Token = authResult.AccessToken, ExpireDate = authResult.ExpiresOn.DateTime }; return(token); } catch (Exception e) { return(null); } }
public static async Task Main(string[] args) { var builder = new ConfigurationBuilder() .AddJsonFile($"appsettings.json", true, true); var configuration = builder.Build(); var azureAdConfiguration = configuration.GetSection("AzureAd"); var options = new ConfidentialClientApplicationOptions() { ClientId = azureAdConfiguration["ClientId"], ClientSecret = azureAdConfiguration["ClientSecret"], Instance = azureAdConfiguration["Instance"], TenantId = azureAdConfiguration["TenantId"] }; var confidentialClientApplication = ConfidentialClientApplicationBuilder .CreateWithApplicationOptions(options) .Build(); var authenticationResult = await confidentialClientApplication.AcquireTokenForClient(new string[] { "https://graph.microsoft.com/.default" }).ExecuteAsync(); var accessToken = authenticationResult.AccessToken; Console.WriteLine(accessToken); var httpClient = new HttpClient() { BaseAddress = new Uri("https://graph.microsoft.com") }; httpClient.SetBearerToken(accessToken); using var request = new HttpRequestMessage { Method = new HttpMethod("GET"), RequestUri = new Uri("v1.0/users", UriKind.RelativeOrAbsolute) }; var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, default); if (response.StatusCode != HttpStatusCode.OK) { Console.WriteLine(response.ToString()); } using var responseStream = await response.Content.ReadAsStreamAsync(); using var streamReader = new StreamReader(responseStream); using var jsonTextReader = new JsonTextReader(streamReader); var serializer = JsonSerializer.Create(); var userReponse = serializer.Deserialize <UserResponse>(jsonTextReader); var users = userReponse.Users; users.ForEach(user => { Console.WriteLine(JsonConvert.SerializeObject(user, Formatting.Indented)); }); Console.WriteLine("Press any key to exit..."); Console.Read(); }
private static async Task RunAsync(string[] args) { // Load configuration. var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false) .AddUserSecrets <Program>(optional: true) .AddEnvironmentVariables() .AddCommandLine(args) .Build(); var sampleApiRootUrl = configuration.GetValue <string>("SampleApiRootUrl"); var sampleApiScope = configuration.GetValue <string>("AzureAd:Scope"); var confidentialClientApplicationOptions = new ConfidentialClientApplicationOptions(); configuration.Bind("AzureAd", confidentialClientApplicationOptions); var scopes = new[] { sampleApiScope }; // The client credentials flow ALWAYS uses the "/.default" scope. while (true) { try { Console.WriteLine("A - Call API using a client secret"); Console.Write("Type your choice and press Enter: "); var choice = Console.ReadLine(); if (string.Equals(choice, "A", StringComparison.InvariantCultureIgnoreCase)) { // Retrieve an access token to call the back-end Web API using a client secret // representing this application (rather than a user). var confidentialClientApplication = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(confidentialClientApplicationOptions).Build(); var token = await confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync(); // Put the access token on the authorization header by default. var client = new HttpClient(); client.BaseAddress = new Uri(sampleApiRootUrl); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken); // Call the back-end Web API using the bearer access token. var response = await client.GetAsync("api/identity"); response.EnsureSuccessStatusCode(); // Deserialize the response into an IdentityInfo instance. var apiResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine("Web API call was successful, raw response:"); Console.WriteLine(apiResponse); } else { break; } Console.WriteLine(); } catch (Exception exc) { Console.WriteLine(exc.ToString()); } } }
/// <summary> /// Creates an MSAL Confidential client application. /// </summary> private async Task <IConfidentialClientApplication> BuildConfidentialClientApplicationAsync() { if (!_applicationOptions.Instance.EndsWith("/", StringComparison.InvariantCulture)) { _applicationOptions.Instance += "/"; } string authority; IConfidentialClientApplication app; MicrosoftIdentityOptionsValidation microsoftIdentityOptionsValidation = new MicrosoftIdentityOptionsValidation(); microsoftIdentityOptionsValidation.ValidateEitherClientCertificateOrClientSecret( _applicationOptions.ClientSecret, _microsoftIdentityOptions.ClientCertificates); try { var builder = ConfidentialClientApplicationBuilder .CreateWithApplicationOptions(_applicationOptions) .WithRedirectUri(CreateRedirectUri()) .WithHttpClientFactory(_httpClientFactory); if (_microsoftIdentityOptions.IsB2C) { authority = $"{_applicationOptions.Instance}tfp/{_microsoftIdentityOptions.Domain}/{_microsoftIdentityOptions.DefaultUserFlow}"; builder.WithB2CAuthority(authority); } else { authority = $"{_applicationOptions.Instance}{_applicationOptions.TenantId}/"; builder.WithAuthority(authority); } if (_microsoftIdentityOptions.ClientCertificates != null) { X509Certificate2 certificate = DefaultCertificateLoader.LoadFirstCertificate(_microsoftIdentityOptions.ClientCertificates); builder.WithCertificate(certificate); } app = builder.Build(); // Initialize token cache providers await _tokenCacheProvider.InitializeAsync(app.AppTokenCache).ConfigureAwait(false); await _tokenCacheProvider.InitializeAsync(app.UserTokenCache).ConfigureAwait(false); return(app); } catch (Exception ex) { _logger.LogInformation( ex, string.Format( CultureInfo.InvariantCulture, "Exception acquiring token for a confidential client. ")); throw; } }
public IConfidentialClientApplication GetApplication() { if (_application == null) { _application = ConfidentialClientApplicationBuilder .CreateWithApplicationOptions(_applicationOptions) .Build(); } return(_application); }
public MsalClientCredentialsProvider(IConfiguration configuration) { var scopes = configuration["Scopes"]; _scopes = scopes.Split(new char[0], StringSplitOptions.RemoveEmptyEntries); var options = new ConfidentialClientApplicationOptions(); configuration.Bind("AzureAd", options); _app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options).Build(); }
public void CacheSynchronizationNoDefault(bool optionFlag, bool builderFlag, bool result) { var options = new ConfidentialClientApplicationOptions { ClientSecret = "secret", ClientId = TestConstants.ClientId, EnableCacheSynchronization = optionFlag }; var app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options).WithCacheSynchronization(builderFlag).Build(); Assert.AreEqual(result, (app.AppConfig as ApplicationConfiguration).CacheSynchronizationEnabled); }
/// <summary> /// Creates an MSAL Confidential client application /// </summary> /// <param name="claimsPrincipal"></param> /// <returns></returns> private async Task <IConfidentialClientApplication> BuildConfidentialClientApplicationAsync() { var request = CurrentHttpContext.Request; string currentUri = UriHelper.BuildAbsolute( request.Scheme, request.Host, request.PathBase, _microsoftIdentityOptions.CallbackPath.Value ?? string.Empty); if (!_applicationOptions.Instance.EndsWith("/")) { _applicationOptions.Instance += "/"; } string authority; IConfidentialClientApplication app; try { if (_microsoftIdentityOptions.IsB2C) { authority = $"{ _applicationOptions.Instance}tfp/{_microsoftIdentityOptions.Domain}/{_microsoftIdentityOptions.DefaultUserFlow}"; app = ConfidentialClientApplicationBuilder .CreateWithApplicationOptions(_applicationOptions) .WithRedirectUri(currentUri) .WithB2CAuthority(authority) .Build(); } else { authority = $"{ _applicationOptions.Instance}{_applicationOptions.TenantId}/"; app = ConfidentialClientApplicationBuilder .CreateWithApplicationOptions(_applicationOptions) .WithRedirectUri(currentUri) .WithAuthority(authority) .Build(); } // Initialize token cache providers await _tokenCacheProvider.InitializeAsync(app.AppTokenCache).ConfigureAwait(false); await _tokenCacheProvider.InitializeAsync(app.UserTokenCache).ConfigureAwait(false); return(app); } catch (Exception ex) { _logger.LogInformation(ex, "Exception acquiring token for a confidential client. "); throw; } }
/// <summary> /// Creates an MSAL Confidential client application /// </summary> /// <param name="httpContext"></param> /// <param name="claimsPrincipal"></param> /// <param name="authenticationProperties"></param> /// <param name="signInScheme"></param> /// <returns></returns> private IConfidentialClientApplication CreateApplication(HttpContext httpContext, ClaimsPrincipal claimsPrincipal) { var request = httpContext.Request; string currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, azureAdOptions.CallbackPath ?? string.Empty); string authority = $"{azureAdOptions.Instance}{azureAdOptions.TenantId}/"; var app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(_applicationOptions) .WithRedirectUri(currentUri) .WithAuthority(authority) .Build(); tokenCacheProvider.EnableSerialization(app.UserTokenCache, httpContext, claimsPrincipal); return(app); }
public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "POST")] HttpRequest req, ILogger log) { try { var serializer = new JsonSerializer(); var message = serializer.Deserialize <JToken>(new JsonTextReader(new StreamReader(req.Body))); var values = JToken.FromObject(new[] { new[] { message.Value <string>("name"), message.Value <string>("rating"), message.Value <string>("comment") } }); var clientApplicationOptions = new ConfidentialClientApplicationOptions() { TenantId = GraphTenantId, ClientId = GraphClientId, ClientSecret = GraphClientSecret, }; var clientApplicationBuilder = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(clientApplicationOptions); var clientApplication = clientApplicationBuilder.Build(); var authenticationResult = await clientApplication.AcquireTokenForClient(GraphScope).ExecuteAsync(); var graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(async msg => { await Task.Run(() => { msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken); }); })); var o4bUser = graphClient.Users[O4BUserPrincipalName]; var o4bExcelFile = o4bUser.Drive.Root.ItemWithPath(O4BExcelFileName); var o4bExcelTable = o4bExcelFile.Workbook.Tables[O4BExcelTableName]; await o4bExcelTable.Rows.Add(values : values).Request().PostAsync(); req.HttpContext.Response.Headers.Add("CARD-ACTION-STATUS", "Responding to the survey was succeeded."); return(new OkResult()); } catch (Exception ex) { log.LogError(ex.ToString()); req.HttpContext.Response.Headers.Add("CARD-ACTION-STATUS", "Responding to the survey was failed."); return(new OkResult()); } }
private void SetupGraphClient(string sectionName, HttpClient c) { var options = new ConfidentialClientApplicationOptions(); Configuration.Bind(sectionName, options); var msal = ConfidentialClientApplicationBuilder .CreateWithApplicationOptions(options) .Build(); var tokens = msal.AcquireTokenForClient(new string[] { "https://graph.microsoft.com/.default" }).ExecuteAsync().Result; c.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", tokens.AccessToken); c.BaseAddress = new Uri("https://graph.microsoft.com/v1.0/"); c.DefaultRequestHeaders.Add("Accept", "application/json"); }
public void TestBuildWithNoClientSecretButUsingCert() { var options = new ConfidentialClientApplicationOptions() { ClientId = TestConstants.ClientId, TenantId = "the_tenant_id", Instance = "https://login.microsoftonline.com" }; var app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options).Build(); var authorityInfo = ((ConfidentialClientApplication)app).ServiceBundle.Config.AuthorityInfo; Assert.AreEqual("https://login.microsoftonline.com/the_tenant_id/", authorityInfo.CanonicalAuthority); }
public async Task <IActionResult> AuthorizeAsync() { // 認証を行うための URL にリダイレクトします var clientApplicationOptions = new ConfidentialClientApplicationOptions() { TenantId = GraphTenantId, ClientId = GraphClientId, ClientSecret = GraphClientSecret, RedirectUri = RedirectUrl }; var clientApplicationBuilder = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(clientApplicationOptions); var clientApplication = clientApplicationBuilder.Build(); var requestUrl = await clientApplication.GetAuthorizationRequestUrl(GraphScope).ExecuteAsync(); return(this.Redirect(requestUrl.ToString())); }
public static IServiceCollection AddEmployerUsersClient(this IServiceCollection services, IConfiguration configuration) { var employerUsersConfig = configuration.GetSection("EmployerUsersApi").Get <EmployerUsersConfiguration>(); services.Configure <EmployerUsersConfiguration>(configuration.GetSection("EmployerUsersApi").Bind); _applicationOptions = new ConfidentialClientApplicationOptions(); configuration.Bind("EmployerUsersApi", _applicationOptions); services.AddSingleton <IConfidentialClientApplication, ConfidentialClientApplication>(x => { var app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(_applicationOptions) .Build(); return(app as ConfidentialClientApplication); }); services.AddTransient <ActiveDirectoryHttpClientHandler>(x => new ActiveDirectoryHttpClientHandler(x.GetRequiredService <IConfidentialClientApplication>(), employerUsersConfig.Identifier)); services.AddTransient <AzureAppAuthenticationHttpClientHandler>(x => new AzureAppAuthenticationHttpClientHandler(employerUsersConfig.Identifier, x.GetRequiredService <ILogger <AzureAppAuthenticationHttpClientHandler> >())); var httpBuilder = services.AddRefitClient <IEmployerUsersApiClient>() .ConfigureHttpClient(c => c.BaseAddress = new Uri(employerUsersConfig.ApiBaseUrl)); var githubClientBuilder = services.AddRefitClient <IGithubRepository>() .ConfigureHttpClient(c => c.BaseAddress = new Uri("https://raw.githubusercontent.com/")); var environment = configuration.GetValue <string>("ASPNETCORE_ENVIRONMENT"); if (environment == "Development") { httpBuilder.AddHttpMessageHandler <ActiveDirectoryHttpClientHandler>(); } else { httpBuilder.AddHttpMessageHandler <AzureAppAuthenticationHttpClientHandler>(); } return(services); }
public void CacheSynchronizationWithDefaultCCA() { //Validate CacheSynchronizationEnabled when app is created from ApplicaitonOptions for CCA var options = new ConfidentialClientApplicationOptions() { ClientSecret = "secret", ClientId = TestConstants.ClientId, }; var app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options).Build(); Assert.IsFalse((app.AppConfig as ApplicationConfiguration).CacheSynchronizationEnabled); options = new ConfidentialClientApplicationOptions { ClientId = TestConstants.ClientId, ClientSecret = "secret", EnableCacheSynchronization = false }; app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options).Build(); Assert.AreEqual(false, (app.AppConfig as ApplicationConfiguration).CacheSynchronizationEnabled); options = new ConfidentialClientApplicationOptions { ClientId = TestConstants.ClientId, ClientSecret = "secret", EnableCacheSynchronization = true }; app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options).Build(); Assert.AreEqual(true, (app.AppConfig as ApplicationConfiguration).CacheSynchronizationEnabled); //Validate CacheSynchronizationEnabled is false by default when app is created from ConfidentialClientApplicationBuilder app = ConfidentialClientApplicationBuilder.Create(Guid.NewGuid().ToString()).WithClientSecret(TestConstants.ClientSecret).BuildConcrete(); Assert.IsFalse((app.AppConfig as ApplicationConfiguration).CacheSynchronizationEnabled); //Validate CacheSynchronizationEnabled when app is created from ApplicaitonOptions for PCA var options2 = new PublicClientApplicationOptions() { ClientId = TestConstants.ClientId }; var app2 = PublicClientApplicationBuilder.CreateWithApplicationOptions(options2).Build(); Assert.IsTrue((app2.AppConfig as ApplicationConfiguration).CacheSynchronizationEnabled); //Validate CacheSynchronizationEnabled is true by default when app is created from PublicClientApplicationBuilder app2 = PublicClientApplicationBuilder.Create(Guid.NewGuid().ToString()).BuildConcrete(); Assert.IsTrue((app2.AppConfig as ApplicationConfiguration).CacheSynchronizationEnabled); }
public void CreateConfidentialClient(string resource, string clientCertificate) { X509Certificate2 certificate = ReadCertificate(clientCertificate); _confidentialClientApp = ConfidentialClientApplicationBuilder .CreateWithApplicationOptions(new ConfidentialClientApplicationOptions { ClientId = Config.AzureClientId, RedirectUri = resource, TenantId = Config.AzureTenantId, ClientName = Config.AzureClientId }) .WithAuthority(AzureCloudInstance.AzurePublic, Config.AzureTenantId) .WithCertificate(certificate) .Build(); AddClientScopes(); }
public void CreateConfidentialCertificateClient(string resource, X509Certificate2 clientCertificate) { Log.Info($"enter: {resource}"); _confidentialClientApp = ConfidentialClientApplicationBuilder .CreateWithApplicationOptions(new ConfidentialClientApplicationOptions { ClientId = _config.AzureClientId, RedirectUri = resource, TenantId = _config.AzureTenantId, ClientName = Constants.ApplicationName }) .WithAuthority(AzureCloudInstance.AzurePublic, _config.AzureTenantId) .WithLogging(MsalLoggerCallback, LogLevel.Verbose, true, true) .WithCertificate(clientCertificate) .Build(); AddClientScopes(true); }
/// <summary> /// Creates an MSAL Confidential client application /// </summary> /// <param name="claimsPrincipal"></param> /// <returns></returns> private IConfidentialClientApplication BuildConfidentialClientApplication() { var request = CurrentHttpContext.Request; var microsoftIdentityOptions = _microsoftIdentityOptions; var applicationOptions = _applicationOptions; string currentUri = UriHelper.BuildAbsolute( request.Scheme, request.Host, request.PathBase, microsoftIdentityOptions.CallbackPath.Value ?? string.Empty); if (!applicationOptions.Instance.EndsWith("/")) { applicationOptions.Instance += "/"; } string authority; IConfidentialClientApplication app = null; if (microsoftIdentityOptions.IsB2C) { authority = $"{applicationOptions.Instance}tfp/{microsoftIdentityOptions.Domain}/{microsoftIdentityOptions.DefaultUserFlow}"; app = ConfidentialClientApplicationBuilder .CreateWithApplicationOptions(applicationOptions) .WithRedirectUri(currentUri) .WithB2CAuthority(authority) .Build(); } else { authority = $"{applicationOptions.Instance}{applicationOptions.TenantId}/"; app = ConfidentialClientApplicationBuilder .CreateWithApplicationOptions(applicationOptions) .WithRedirectUri(currentUri) .WithAuthority(authority) .Build(); } // Initialize token cache providers _tokenCacheProvider?.InitializeAsync(app.AppTokenCache); _tokenCacheProvider?.InitializeAsync(app.UserTokenCache); return(app); }
public IConfidentialClientApplication CreateConfidentialClientApplication() { var options = serviceProvider .GetRequiredService <IOptions <ConfidentialClientApplicationOptions> >() .Value; var builder = ConfidentialClientApplicationBuilder .CreateWithApplicationOptions(options); ConfigureBuilder(builder); var app = builder.Build(); var cacheStorageProvider = serviceProvider.GetService <MsalTokenCacheProvider>(); if (cacheStorageProvider is not null) { cacheStorageProvider.RegisterCache(app.UserTokenCache); cacheStorageProvider.RegisterCache(app.AppTokenCache); } return(app); }
public void TestBuildWithNoClientSecretButUsingCert() { var options = new ConfidentialClientApplicationOptions() { ClientId = TestConstants.ClientId, TenantId = "the_tenant_id", Instance = "https://login.microsoftonline.com", }; var cert = new X509Certificate2( ResourceHelper.GetTestResourceRelativePath("testCert.crtfile"), "passw0rd!"); var app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options) .WithCertificate(cert) .Build(); var authorityInfo = ((ConfidentialClientApplication)app).ServiceBundle.Config.AuthorityInfo; Assert.AreEqual("https://login.microsoftonline.com/the_tenant_id/", authorityInfo.CanonicalAuthority); }
[DataRow(null)] // Not specified, default is true public void TestConstructor_WithLegacyCacheCompatibility_WithOptions(bool?isLegacyCacheCompatibilityEnabled) { var options = CreateConfidentialClientApplicationOptions(); if (isLegacyCacheCompatibilityEnabled.HasValue) { options.LegacyCacheCompatibilityEnabled = isLegacyCacheCompatibilityEnabled.Value; } else { isLegacyCacheCompatibilityEnabled = true; } var cca = ConfidentialClientApplicationBuilder .CreateWithApplicationOptions(options) .Build(); Assert.AreEqual(isLegacyCacheCompatibilityEnabled, cca.AppConfig.LegacyCacheCompatibilityEnabled); }
public void CreateConfidentialClient(string resource, string secret) { Log.Info($"enter: {resource}"); // no prompt with clientid and secret _confidentialClientApp = ConfidentialClientApplicationBuilder .CreateWithApplicationOptions(new ConfidentialClientApplicationOptions { ClientId = _config.AzureClientId, RedirectUri = resource, ClientSecret = secret, TenantId = _config.AzureTenantId, ClientName = _config.AzureClientId }) .WithAuthority(AzureCloudInstance.AzurePublic, _config.AzureTenantId) .WithLogging(MsalLoggerCallback, LogLevel.Verbose, true, true) .Build(); AddClientScopes(); }