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);
        }
예제 #2
0
 /// <summary>
 /// Constructor of the TokenAcquisition service. This requires the Azure AD Options to
 /// configure the confidential client application and a token cache provider.
 /// This constructor is called by ASP.NET Core dependency injection
 /// </summary>
 /// <param name="configuration"></param>
 /// <param name="appTokenCacheProvider">The App token cache provider</param>
 /// <param name="userTokenCacheProvider">The User token cache provider</param>
 public TokenAcquisition(
     IMsalAppTokenCacheProvider appTokenCacheProvider,
     IMsalUserTokenCacheProvider userTokenCacheProvider,
     IHttpContextAccessor httpContextAccessor,
     IOptions <AzureADOptions> azureAdOptions,
     IOptions <ConfidentialClientApplicationOptions> applicationOptions)
 {
     _httpContextAccessor    = httpContextAccessor;
     _azureAdOptions         = azureAdOptions.Value;
     _applicationOptions     = applicationOptions.Value;
     _appTokenCacheProvider  = appTokenCacheProvider;
     _userTokenCacheProvider = userTokenCacheProvider;
 }
 /// <summary>
 /// Constructor of the TokenAcquisition service. This requires the Azure AD Options to
 /// configure the confidential client application and a token cache provider.
 /// This constructor is called by ASP.NET Core dependency injection
 /// </summary>
 /// <param name="configuration"></param>
 /// <param name="tokenCacheProvider">The App token cache provider</param>
 /// <param name="userTokenCacheProvider">The User token cache provider</param>
 public TokenAcquisition(
     IMsalTokenCacheProvider tokenCacheProvider,
     IHttpContextAccessor httpContextAccessor,
     IOptions <MicrosoftIdentityOptions> microsoftIdentityOptions,
     IOptions <ConfidentialClientApplicationOptions> applicationOptions,
     ILogger <TokenAcquisition> logger)
 {
     _httpContextAccessor      = httpContextAccessor;
     _microsoftIdentityOptions = microsoftIdentityOptions.Value;
     _applicationOptions       = applicationOptions.Value;
     _tokenCacheProvider       = tokenCacheProvider;
     _logger = logger;
 }
예제 #4
0
        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());
            }
        }
예제 #5
0
        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);
        }
예제 #6
0
        /// <summary>
        /// Constructor of the TokenAcquisition service. This requires the Azure AD Options to
        /// configure the confidential client application and a token cache provider.
        /// This constructor is called by ASP.NET Core dependency injection
        /// </summary>
        /// <param name="appTokenCacheProvider">The App token cache provider</param>
        /// <param name="userTokenCacheProvider">The User token cache provider</param>
        /// <param name="configuration"></param>
        public TokenAcquisition(
            IConfiguration configuration,
            IMsalAppTokenCacheProvider appTokenCacheProvider,
            IMsalUserTokenCacheProvider userTokenCacheProvider)
        {
            _azureAdOptions = new AzureADOptions();
            configuration.Bind("AzureAD", _azureAdOptions);

            _applicationOptions = new ConfidentialClientApplicationOptions();
            configuration.Bind("AzureAD", _applicationOptions);

            _appTokenCacheProvider  = appTokenCacheProvider;
            _userTokenCacheProvider = userTokenCacheProvider;
        }
예제 #7
0
        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");
        }
예제 #8
0
        /// <summary>
        /// Constructor of the TokenAcquisition service. This requires the Azure AD Options to
        /// configure the confidential client application and a token cache provider.
        /// This constructor is called by ASP.NET Core dependency injection
        /// </summary>
        /// <param name="appTokenCacheProvider">The App token cache provider</param>
        /// <param name="userTokenCacheProvider">The User token cache provider</param>
        /// <param name="configuration"></param>
        public TokenAcquisition(IConfiguration configuration, IMSALAppTokenCacheProvider appTokenCacheProvider, IMSALUserTokenCacheProvider userTokenCacheProvider)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            azureAdOptions = new AzureADOptions();
            configuration.Bind("AzureAD", azureAdOptions);

            _applicationOptions = new ConfidentialClientApplicationOptions();
            configuration.Bind("AzureAD", _applicationOptions);

            this.AppTokenCacheProvider  = appTokenCacheProvider;
            this.UserTokenCacheProvider = userTokenCacheProvider;
        }
        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()));
        }
예제 #10
0
        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);
        }
예제 #12
0
 /// <summary>
 /// Constructor of the TokenAcquisition service. This requires the Azure AD Options to
 /// configure the confidential client application and a token cache provider.
 /// This constructor is called by ASP.NET Core dependency injection.
 /// </summary>
 /// <param name="tokenCacheProvider">The App token cache provider.</param>
 /// <param name="httpContextAccessor">Access to the HttpContext of the request.</param>
 /// <param name="microsoftIdentityOptions">Configuration options.</param>
 /// <param name="applicationOptions">MSAL.NET configuration options.</param>
 /// <param name="httpClientFactory">HTTP client factory.</param>
 /// <param name="logger">Logger.</param>
 /// <param name="serviceProvider">Service provider.</param>
 public TokenAcquisition(
     IMsalTokenCacheProvider tokenCacheProvider,
     IHttpContextAccessor httpContextAccessor,
     IOptions <MicrosoftIdentityOptions> microsoftIdentityOptions,
     IOptions <ConfidentialClientApplicationOptions> applicationOptions,
     IHttpClientFactory httpClientFactory,
     ILogger <TokenAcquisition> logger,
     IServiceProvider serviceProvider)
 {
     _httpContextAccessor      = httpContextAccessor;
     _microsoftIdentityOptions = microsoftIdentityOptions.Value;
     _applicationOptions       = applicationOptions.Value;
     _tokenCacheProvider       = tokenCacheProvider;
     _httpClientFactory        = new MsalAspNetCoreHttpClientFactory(httpClientFactory);
     _logger          = logger;
     _serviceProvider = serviceProvider;
 }
        private void BuildTheRequiredServices(string instance = TestConstants.AadInstance)
        {
            var services = new ServiceCollection();

            _applicationOptions = new ConfidentialClientApplicationOptions
            {
                Instance     = instance,
                ClientId     = TestConstants.ConfidentialClientId,
                ClientSecret = TestConstants.ClientSecret,
            };

            services.AddTokenAcquisition();
            services.AddTransient(
                provider => Options.Create(_microsoftIdentityOptions));
            services.AddTransient(
                provider => Options.Create(_applicationOptions));
            _provider = services.BuildServiceProvider();
        }
예제 #14
0
        public void ValidateCredentialType()
        {
            // Arrange
            MicrosoftIdentityOptions microsoftIdentityOptions = new MicrosoftIdentityOptions
            {
                Authority = TestConstants.AuthorityCommonTenant,
                ClientId  = TestConstants.ConfidentialClientId,
            };

            ConfidentialClientApplicationOptions options = new ConfidentialClientApplicationOptions
            {
                ClientSecret = "some secret",
            };

            // Act & Assert
            // Should not throw
            MicrosoftIdentityOptionsValidation.ValidateEitherClientCertificateOrClientSecret(options.ClientSecret, microsoftIdentityOptions.ClientCertificates);
        }
예제 #15
0
        private IConfidentialClientApplication GetOrCreateApplication()
        {
            if (_confidentialClientApplication == null)
            {
                ConfidentialClientApplicationOptions options = new ConfidentialClientApplicationOptions()
                {
                    ClientId     = AppServicesAuthenticationInformation.ClientId,
                    ClientSecret = AppServicesAuthenticationInformation.ClientSecret,
                    Instance     = AppServicesAuthenticationInformation.Issuer,
                };
                _confidentialClientApplication = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options)
                                                 .WithHttpClientFactory(_httpClientFactory)
                                                 .Build();
                _tokenCacheProvider.Initialize(_confidentialClientApplication.AppTokenCache);
                _tokenCacheProvider.Initialize(_confidentialClientApplication.UserTokenCache);
            }

            return(_confidentialClientApplication);
        }
예제 #16
0
        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);
        }
        public async Task <IActionResult> CallbackAsync(string code, string error, [FromQuery(Name = "error_description")] string description, string resource, string state)
        {
            // アクセス トークンを取得します
            var clientApplicationOptions = new ConfidentialClientApplicationOptions()
            {
                TenantId     = GraphTenantId,
                ClientId     = GraphClientId,
                ClientSecret = GraphClientSecret,
                RedirectUri  = RedirectUrl
            };
            var clientApplicationBuilder = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(clientApplicationOptions);
            var clientApplication        = clientApplicationBuilder.Build();
            var authenticationResult     = await clientApplication.AcquireTokenByAuthorizationCode(GraphScope, code).ExecuteAsync();

            // アクセス トークンをセッションに格納します
            var accessToken = authenticationResult.AccessToken;

            this.HttpContext.Session.Set("access_token", Encoding.UTF8.GetBytes(accessToken));

            return(this.RedirectToAction("Index", "Home"));
        }
예제 #18
0
        public Worker(ILogger <Worker> logger,
                      IHttpClientFactory http,
                      IConfiguration config,
                      IOptions <AzureAdOptions> azureAdConfig)
        {
            _logger          = logger;
            _http            = http;
            _usersApiBaseUrl = config.GetValue <string>("Services:UsersApiUrl");

            var co = new ConfidentialClientApplicationOptions
            {
                Instance     = "https://login.microsoftonline.com/",
                TenantId     = "6b9be1b6-4f80-4ce7-8479-16c4d7726470",
                ClientId     = azureAdConfig.Value.ClientId,
                ClientSecret = azureAdConfig.Value.ClientSecret
            };

            //todo configure cache
            _clientApplication = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(co)
                                 .Build();
        }
예제 #19
0
        public void ValidateCredentialType_Certificate(string base64Encoded)
        {
            // Arrange
            CertificateDescription certificateDescription =
                CertificateDescription.FromBase64Encoded(base64Encoded);

            MicrosoftIdentityOptions microsoftIdentityOptions = new MicrosoftIdentityOptions
            {
                Authority          = TestConstants.AuthorityCommonTenant,
                ClientId           = TestConstants.ConfidentialClientId,
                ClientCertificates = new CertificateDescription[] { certificateDescription },
            };

            ConfidentialClientApplicationOptions options = new ConfidentialClientApplicationOptions
            {
                ClientSecret = string.Empty,
            };

            // Act & Assert
            // Should not throw
            MicrosoftIdentityOptionsValidation.ValidateEitherClientCertificateOrClientSecret(options.ClientSecret, microsoftIdentityOptions.ClientCertificates);
        }
        public void ApplicationOptionsIncludeClientSecret(string clientSecret)
        {
            // Arrange
            InitializeTokenAcquisitionObjects();

            var options = new ConfidentialClientApplicationOptions
            {
                ClientSecret = clientSecret
            };

            MicrosoftIdentityOptionsValidation microsoftIdentityOptionsValidation = new MicrosoftIdentityOptionsValidation();
            ValidateOptionsResult result = microsoftIdentityOptionsValidation.ValidateClientSecret(options);

            if (result.Failed)
            {
                string msg = string.Format(CultureInfo.InvariantCulture, "The 'ClientSecret' option must be provided.");
                Assert.Equal(msg, result.FailureMessage);
            }
            else
            {
                Assert.True(result.Succeeded);
            }
        }
예제 #21
0
        private void BuildTheRequiredServices()
        {
            var services = new ServiceCollection();

            _applicationOptions = new ConfidentialClientApplicationOptions
            {
                Instance     = TestConstants.AadInstance,
                ClientId     = TestConstants.ConfidentialClientId,
                ClientSecret = "cats",
            };

            services.AddTokenAcquisition();
            services.AddTransient(
                provider => Options.Create(new MicrosoftIdentityOptions
            {
                Authority    = TestConstants.AuthorityCommonTenant,
                ClientId     = TestConstants.ConfidentialClientId,
                CallbackPath = string.Empty,
            }));
            services.AddTransient(
                provider => Options.Create(_applicationOptions));
            _provider = services.BuildServiceProvider();
        }
        /// <summary>
        /// Constructor of the TokenAcquisition service. This requires the Azure AD Options to
        /// configure the confidential client application and a token cache provider.
        /// This constructor is called by ASP.NET Core dependency injection.
        /// </summary>
        /// <param name="tokenCacheProvider">The App token cache provider.</param>
        /// <param name="httpContextAccessor">Access to the HttpContext of the request.</param>
        /// <param name="microsoftIdentityOptions">Configuration options.</param>
        /// <param name="applicationOptions">MSAL.NET configuration options.</param>
        /// <param name="httpClientFactory">HTTP client factory.</param>
        /// <param name="logger">Logger.</param>
        /// <param name="serviceProvider">Service provider.</param>
        public TokenAcquisition(
            IMsalTokenCacheProvider tokenCacheProvider,
            IHttpContextAccessor httpContextAccessor,
            IOptions <MicrosoftIdentityOptions> microsoftIdentityOptions,
            IOptions <ConfidentialClientApplicationOptions> applicationOptions,
            IHttpClientFactory httpClientFactory,
            ILogger <TokenAcquisition> logger,
            IServiceProvider serviceProvider)
        {
            _httpContextAccessor      = httpContextAccessor;
            _microsoftIdentityOptions = microsoftIdentityOptions.Value;
            _applicationOptions       = applicationOptions.Value;
            _tokenCacheProvider       = tokenCacheProvider;
            _httpClientFactory        = new MsalAspNetCoreHttpClientFactory(httpClientFactory);
            _logger          = logger;
            _serviceProvider = serviceProvider;

            _applicationOptions.ClientId ??= _microsoftIdentityOptions.ClientId;
            _applicationOptions.Instance ??= _microsoftIdentityOptions.Instance;
            _applicationOptions.ClientSecret ??= _microsoftIdentityOptions.ClientSecret;
            _applicationOptions.TenantId ??= _microsoftIdentityOptions.TenantId;
            _applicationOptions.LegacyCacheCompatibilityEnabled          = _microsoftIdentityOptions.LegacyCacheCompatibilityEnabled;
            DefaultCertificateLoader.UserAssignedManagedIdentityClientId = _microsoftIdentityOptions.UserAssignedManagedIdentityClientId;
        }
예제 #23
0
        public void NoCredentialTypesDefined_Throw()
        {
            // Arrange
            MicrosoftIdentityOptions microsoftIdentityOptions = new MicrosoftIdentityOptions
            {
                Authority = TestConstants.AuthorityCommonTenant,
                ClientId  = TestConstants.ConfidentialClientId,
            };

            ConfidentialClientApplicationOptions options = new ConfidentialClientApplicationOptions
            {
                ClientSecret = string.Empty,
            };

            // Act
            Action credentialAction = () =>
                                      MicrosoftIdentityOptionsValidation.ValidateEitherClientCertificateOrClientSecret(options.ClientSecret, microsoftIdentityOptions.ClientCertificates);

            // Assert
            var exception = Assert.Throws <MsalClientException>(credentialAction);

            Assert.Equal(IDWebErrorMessage.ClientSecretAndCertficateNull, exception.Message);
            Assert.Equal(ErrorCodes.MissingClientCredentials, exception.ErrorCode);
        }
        internal static void UpdateMergedOptionsFromConfidentialClientApplicationOptions(ConfidentialClientApplicationOptions confidentialClientApplicationOptions, MergedOptions mergedOptions)
        {
            mergedOptions.MergedWithCca        = true;
            mergedOptions.AadAuthorityAudience = confidentialClientApplicationOptions.AadAuthorityAudience;
            mergedOptions.AzureCloudInstance   = confidentialClientApplicationOptions.AzureCloudInstance;
            if (string.IsNullOrEmpty(mergedOptions.AzureRegion) && !string.IsNullOrEmpty(confidentialClientApplicationOptions.AzureRegion))
            {
                mergedOptions.AzureRegion = confidentialClientApplicationOptions.AzureRegion;
            }

            mergedOptions.ClientCapabilities ??= confidentialClientApplicationOptions.ClientCapabilities;
            if (string.IsNullOrEmpty(mergedOptions.ClientId) && !string.IsNullOrEmpty(confidentialClientApplicationOptions.ClientId))
            {
                mergedOptions.ClientId = confidentialClientApplicationOptions.ClientId;
            }

            if (string.IsNullOrEmpty(mergedOptions.ClientName) && !string.IsNullOrEmpty(confidentialClientApplicationOptions.ClientName))
            {
                mergedOptions.ClientName = confidentialClientApplicationOptions.ClientName;
            }

            if (string.IsNullOrEmpty(mergedOptions.ClientSecret) && !string.IsNullOrEmpty(confidentialClientApplicationOptions.ClientSecret))
            {
                mergedOptions.ClientSecret = confidentialClientApplicationOptions.ClientSecret;
            }

            if (string.IsNullOrEmpty(mergedOptions.ClientVersion) && !string.IsNullOrEmpty(confidentialClientApplicationOptions.ClientVersion))
            {
                mergedOptions.ClientVersion = confidentialClientApplicationOptions.ClientVersion;
            }

            mergedOptions.EnablePiiLogging = confidentialClientApplicationOptions.EnablePiiLogging;
            if (string.IsNullOrEmpty(mergedOptions.Instance) && !string.IsNullOrEmpty(confidentialClientApplicationOptions.Instance))
            {
                mergedOptions.Instance = confidentialClientApplicationOptions.Instance;
            }

            mergedOptions.IsDefaultPlatformLoggingEnabled = confidentialClientApplicationOptions.IsDefaultPlatformLoggingEnabled;
            // mergedOptions.LegacyCacheCompatibilityEnabled = confidentialClientApplicationOptions.LegacyCacheCompatibilityEnabled; // must be set through id web options
            mergedOptions.EnableCacheSynchronization = confidentialClientApplicationOptions.EnableCacheSynchronization;
            mergedOptions.LogLevel = confidentialClientApplicationOptions.LogLevel;
            if (string.IsNullOrEmpty(mergedOptions.RedirectUri) && !string.IsNullOrEmpty(confidentialClientApplicationOptions.RedirectUri))
            {
                mergedOptions.RedirectUri = confidentialClientApplicationOptions.RedirectUri;
            }

            if (string.IsNullOrEmpty(mergedOptions.TenantId) && !string.IsNullOrEmpty(confidentialClientApplicationOptions.TenantId))
            {
                mergedOptions.TenantId = confidentialClientApplicationOptions.TenantId;
            }

            mergedOptions._confidentialClientApplicationOptions = null;
        }
        internal static void UpdateConfidentialClientApplicationOptionsFromMergedOptions(MergedOptions mergedOptions, ConfidentialClientApplicationOptions confidentialClientApplicationOptions)
        {
            confidentialClientApplicationOptions.AadAuthorityAudience = mergedOptions.AadAuthorityAudience;
            confidentialClientApplicationOptions.AzureCloudInstance   = mergedOptions.AzureCloudInstance;
            if (string.IsNullOrEmpty(confidentialClientApplicationOptions.AzureRegion) && !string.IsNullOrEmpty(mergedOptions.AzureRegion))
            {
                confidentialClientApplicationOptions.AzureRegion = mergedOptions.AzureRegion;
            }

            confidentialClientApplicationOptions.ClientCapabilities ??= mergedOptions.ClientCapabilities;
            if (string.IsNullOrEmpty(confidentialClientApplicationOptions.ClientId) && !string.IsNullOrEmpty(mergedOptions.ClientId))
            {
                confidentialClientApplicationOptions.ClientId = mergedOptions.ClientId;
            }

            if (string.IsNullOrEmpty(confidentialClientApplicationOptions.ClientName) && !string.IsNullOrEmpty(mergedOptions.ClientName))
            {
                confidentialClientApplicationOptions.ClientName = mergedOptions.ClientName;
            }

            if (string.IsNullOrEmpty(confidentialClientApplicationOptions.ClientSecret) && !string.IsNullOrEmpty(mergedOptions.ClientSecret))
            {
                confidentialClientApplicationOptions.ClientSecret = mergedOptions.ClientSecret;
            }

            if (string.IsNullOrEmpty(confidentialClientApplicationOptions.ClientVersion) && !string.IsNullOrEmpty(mergedOptions.ClientVersion))
            {
                confidentialClientApplicationOptions.ClientVersion = mergedOptions.ClientVersion;
            }

            confidentialClientApplicationOptions.EnablePiiLogging = mergedOptions.EnablePiiLogging;
            if (string.IsNullOrEmpty(confidentialClientApplicationOptions.Instance) && !string.IsNullOrEmpty(mergedOptions.Instance))
            {
                confidentialClientApplicationOptions.Instance = mergedOptions.Instance;
            }

            confidentialClientApplicationOptions.IsDefaultPlatformLoggingEnabled = mergedOptions.IsDefaultPlatformLoggingEnabled;
            confidentialClientApplicationOptions.LegacyCacheCompatibilityEnabled = mergedOptions.LegacyCacheCompatibilityEnabled;
            confidentialClientApplicationOptions.EnableCacheSynchronization      = mergedOptions.EnableCacheSynchronization;
            confidentialClientApplicationOptions.LogLevel = mergedOptions.LogLevel;
            if (string.IsNullOrEmpty(confidentialClientApplicationOptions.RedirectUri) && !string.IsNullOrEmpty(mergedOptions.RedirectUri))
            {
                confidentialClientApplicationOptions.RedirectUri = mergedOptions.RedirectUri;
            }

            if (string.IsNullOrEmpty(confidentialClientApplicationOptions.TenantId) && !string.IsNullOrEmpty(mergedOptions.TenantId))
            {
                confidentialClientApplicationOptions.TenantId = mergedOptions.TenantId;
            }
        }
예제 #26
0
 public ConfidentialClientApplicationProvider(IOptions <ConfidentialClientApplicationOptions> options)
 {
     _applicationOptions = options.Value;
 }