c# - ASP.NET Core 3.1 Azure AD 身份验证抛出 OptionsValidationException

标签 c# .net azure asp.net-core

我正在尝试使用 Azure Active Directory 处理 Web 应用上的身份验证。但是,当我尝试使用 AuthorizeAttribute 进行操作时,应用程序抛出 OptionsValidationException 。出现以下错误:

Microsoft.Extensions.Options.OptionsValidationException: The 'Instance' option must be provided.
   at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)
   at Microsoft.Extensions.Options.OptionsMonitor`1.<>c__DisplayClass11_0.<Get>b__0()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
   at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.get_Value()
   at Microsoft.Extensions.Options.OptionsCache`1.GetOrAdd(String name, Func`1 createOptions)
   at Microsoft.Extensions.Options.OptionsMonitor`1.Get(String name)
   at Microsoft.AspNetCore.Authentication.AzureAD.UI.AzureADOpenIdConnectOptionsConfiguration.Configure(String name, OpenIdConnectOptions options)
   at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)
   at Microsoft.Extensions.Options.OptionsMonitor`1.<>c__DisplayClass11_0.<Get>b__0()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
   at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.get_Value()
   at Microsoft.Extensions.Options.OptionsCache`1.GetOrAdd(String name, Func`1 createOptions)
   at Microsoft.Extensions.Options.OptionsMonitor`1.Get(String name)
   at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.InitializeAsync(AuthenticationScheme scheme, HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationHandlerProvider.GetHandlerAsync(HttpContext context, String authenticationScheme)
   at Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, String scheme, AuthenticationProperties properties)
   at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.ChallengeAsync(AuthenticationProperties properties)
   at Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, String scheme, AuthenticationProperties properties)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

我不知道是什么原因造成的。代码如下:

添加对 Microsoft.AspNetCore.Authentication.AzureAD.UI 的包引用版本3.1.1。

启动类

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(defaultScheme: AzureADDefaults.AuthenticationScheme)
        .AddAzureAD(options =>
        {
            options.ClientId = "<client_id_goes_here>";
            options.TenantId = "<tenant_id_goes_here>";
        });

    services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseDeveloperExceptionPage();
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints => endpoints.MapControllers());
}

家庭 Controller

仅使用一个 Controller 。

public class HomeController : Controller
{
    [Route("")]
    [AllowAnonymous]
    public string Index() => "Hello Anonymous User!";

    [Route("restricted")]
    [Authorize]
    public string Restricted() => $"Hello, {User.Identity.Name}.";
}

当您运行应用程序并点击“索引”操作时,您会得到异常输出:

Hello Anonymous User!

当您到达 /restricted 端点时,就会引发异常。

最佳答案

您没有提供 Microsoft.AspNetCore.Authentication.AzureAD.UI 的多个配置Azure AD 身份验证中需要,例如 Instance , CallbackPath 。您可以修改您的代码如下:

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
        .AddAzureAD(options => Configuration.Bind("AzureAd", options));

然后在 appsettings.json ,添加吹气配置:

"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "xxxx.onmicrosoft.com",
    "TenantId": "xxxxxx-a2dd-4fde-bf8f-f75ab18b21ac",
    "ClientId": "xxxxxxxxx-a9bb-4722-b615-6dcbdc646326",
    "CallbackPath": "/signin-oidc"
},

当然,您应该在Azure门户中提供真实的domian/tenant/clientid并注册https://localhost:xxx/signin-oidc作为门户中的重定向网址。

另一种方法是使用 Azure AD 身份验证模板:新建 ASP.NET Core 应用程序 --> 选择 MVC/Razor 模板 --> 更改身份验证 --> 工作或学校帐户 --> 选择您的租户,模板将有所帮助配置您的应用程序以实现 Azure AD 身份验证。

关于c# - ASP.NET Core 3.1 Azure AD 身份验证抛出 OptionsValidationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60178378/

相关文章:

c# - 将 Ninject 与 MVC 3 一起使用的最佳方法是什么?如何使用?

c# - Fluent Migrator 单元测试 : Holding onto Connection

c# - 如何将单个对象[]传递给参数对象[]

c# - System.DateTime 种类位

azure - 在Azure的应用程序服务中部署Web应用程序

xcode - 从 xcode 登录 azure devops 帐户

c# - c# .net 中的 tabindex 问题

c# - 继承与类型转换

c# - 在 winform 中播放和暂停 .GIF 动画

Azure 表更新并发问题