如何替换 .NET Core 3.0 中的 AddJwtBearer 扩展

How to replace AddJwtBearer extension in .NET Core 3.0

我有以下代码可以在 .NET Core 2.2 中编译和运行:

  byte[] key = Encoding.ASCII.GetBytes(Constants.JWT_SECRET); 
        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(x =>
        {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

在 .NET Core 3.0 中出现错误:

Error CS1061 'AuthenticationBuilder' does not contain a definition for 'AddJwtBearer' and no accessible extension method 'AddJwtBearer' accepting a first argument of type 'AuthenticationBuilder' could be found (are you missing a using directive or an assembly reference?)

当我查看 MSFT 文档时: https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.jwtbearerextensions.addjwtbearer?view=aspnetcore-2.2

并尝试升级到 3.0 版,这似乎是定义 this 的最后一个版本。如何将 AddJwtBearer 迁移到 Core 3.0?

您必须将 Microsoft.AspNetCore.Authentication.JwtBearer 包包含到您的项目中。 Core 3.0 及以上版本为 3.0.0。

如 Mert Sayin 所说,包括包 Microsoft.AspNetCore.Authentication.JwtBearer,但使用 版本 3.0.0

像这样:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => Configuration.Bind("JwtSettings", options)) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => Configuration.Bind("CookieSettings", options));

从这里开始: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/?view=aspnetcore-3.1