将API迁移到.net Core 3的JWT 401未经授权的错误

时间:2019-12-25 16:18:44

标签: c# .net-core jwt webapi

我正在将Web API从.net core 2迁移到3.1,并且对[Authorize]必需的端点有问题。即使发送授权载体令牌,我也会得到401未经授权。 我认为我需要在启动类上配置服务的方式进行一些更改,但无法弄清楚。

这是我的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令牌验证的中间件已经到位。 有什么建议么? 谢谢!

1 个答案:

答案 0 :(得分:1)

尝试添加以下代码段:

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