将 API 迁移到 .net Core 3 时出现 JWT 401 未授权错误

JWT 401 unauthorized error on migrating API to .net Core 3

我正在努力将 Web API 从 .net core 2 迁移到 3.1,但 [Authorize] 请求端点有问题。即使我正在发送授权持有者令牌,我也会收到 401 unauthorized。 我想我需要更改启动时配置服务的方式 class,但无法弄清楚。

这是我的 Startup.cs 文件:

public class Startup
{
    public Startup(IWebHostEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,

                        ValidIssuer = "OhmioWEBApi",
                        ValidAudience = "OhmioWEBClient",
                        IssuerSigningKey = JwtSecurityKey.Create("Secret_key")
                    };

                    options.Events = new JwtBearerEvents
                    {
                        OnAuthenticationFailed = context =>
                        {
                            Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                            return Task.CompletedTask;
                        },
                        OnTokenValidated = context =>
                        {
                            Console.WriteLine("OnTokenValidated: " + context.SecurityToken);
                            return Task.CompletedTask;
                        }
                    };
                });            

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        services.AddSingleton<IConfiguration>(Configuration);

        services.AddAutoMapper(typeof(MapsProfile));

        EntityFrameworkConfiguration.ConfigureService(services, Configuration);
        IocContainerConfiguration.ConfigureService(services);

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseAuthorization();            

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });            
    }
}

如您所见,用于 JWT 令牌验证的中间件已就位。 有什么建议么? 谢谢!

尝试添加以下代码片段:

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