【问题标题】:Why does ApiAuthorization not work in .NET 5为什么 ApiAuthorization 在 .NET 5 中不起作用
【发布时间】:2020-12-06 10:46:48
【问题描述】:

我从 3.1 版开始使用 .NET Core API 授权,在我将项目升级到 .NET 5 之前一直运行良好。更新后,我收到了 NullReferenceException。

这是 Startup.cs 中的代码:

配置服务

services.AddDbContext(options =>
    options.UseInMemoryDatabase("Databaase"));

services.AddDefaultIdentity()
    .AddEntityFrameworkStores();

services.AddIdentityServer()
    .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.RequireHttpsMetadata = false;
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = configuration["Jwt:Issuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:SecretKey"])),
            ValidAudience = configuration["Jwt:Audience"],
            ValidateAudience = true,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero // Override the default clock skew of 5 mins
        };
    });

配置

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

这是我的DbContext

public class ApplicationDbContext : ApiAuthorizationDbContext

DbContext 构造函数

public ApplicationDbContext(DbContextOptions options, IOptions operationalStoreOptions, ICurrentUserService currentUserService, IDateTime dateTime) : base(options, operationalStoreOptions)
{
    _currentUserService = currentUserService;
    _dateTime = dateTime;
}

我收到了一个NullReferenceException,其中包含以下错误详细信息:

Object reference not set to an instance of an object.
    Microsoft.Extensions.DependencyInjection.ConfigureApiResources.GetApiResources()+MoveNext()
    Microsoft.Extensions.DependencyInjection.ConfigureApiResources.Configure(ApiAuthorizationOptions options)

编辑: GitHub上提出的问题https://github.com/dotnet/aspnetcore/issues/28456

【问题讨论】:

  • 异常消息是否为您提供了为空的特定参数?您如何将范围缩小到导致问题的授权?
  • 代码在哪里抛出异常?
  • 当我运行应用程序时,错误显示在浏览器中。异常不在任何特定的代码行。

标签: c# asp.net-core .net-5 asp.net-core-5.0


【解决方案1】:

您的 AddDefaultIdentity 应该是这样的

services.AddIdentity<ApplicationUser, IdentityRole>()
   .AddEntityFrameworkStores<ApplicationDbContext>();

并删除

services.AddIdentityServer()
    .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

它应该可以工作

【讨论】:

  • 感谢您的回答@ahmed-mohammed。我想知道我是否需要从任何其他类继承我的ApplicationDbContext,因为它目前继承自ApiAuthorizationDbContext?
  • 我进行了建议的更改,但不幸的是它仍然无法正常工作。感谢您的时间。
  • @DotnetDeveloper 是的,我将 ApiAuthorizationDbContext 更改为 IdentityDbContext 但我不记得为什么浏览器控制台对解决这个问题非常有帮助
【解决方案2】:

如果有人正在寻找此问题的解决方案,根据更新中提供的 Github 链接,问题已通过添加 Key 和 .AddIdentityServerJwt() 得到解决

密钥必须添加到appsettings.Development.json,如下所示:

"IdentityServer": {
    "Key": {
      "Type": "Development"
    }
  }

还将Startup.cs 修改为包含.AddIdentityServerJwt():

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddIdentityServerJwt()
    .AddJwtBearer(options =>
    {
        options.RequireHttpsMetadata = false;
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = configuration["Jwt:Issuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:SecretKey"])),
            ValidAudience = configuration["Jwt:Audience"],
            ValidateAudience = true,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero // Override the default clock skew of 5 mins
        };
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    • 2023-01-20
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多