Why does ApiAuthorization not work in .NET 5

Viewed 934

I am using .NET Core API Authorization since version 3.1, which was working fine until I upgraded my project to .NET 5. After updating, I have been getting a NullReferenceException.

Here is the code from Startup.cs:

ConfigureServices

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
        };
    });

Configure

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

This is my DbContext

public class ApplicationDbContext : ApiAuthorizationDbContext

DbContext Constructor

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

I am getting a NullReferenceException with following error details:

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

Edit: Issue raised on GitHub https://github.com/dotnet/aspnetcore/issues/28456

2 Answers

your AddDefaultIdentity should be something like this

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

and remove

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

and it should work

In case someone is looking for the solution for this issue, as per the Github link provided in update, the issue was resolved by adding Key and .AddIdentityServerJwt()

Key must be be added to appsettings.Development.json as below:

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

Also modifying the Startup.cs to include .AddIdentityServerJwt() as:

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
        };
    });
Related