【问题标题】:JWT 401 unauthorized error on migrating API to .net Core 3将 API 迁移到 .net Core 3 时出现 JWT 401 未经授权的错误
【发布时间】:2019-12-25 16:18:44
【问题描述】:

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

【问题讨论】:

标签: c# .net-core jwt webapi


【解决方案1】:

尝试添加以下代码sn-p:

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

【讨论】:

  • 谢谢,结果还是一样:401未授权
  • 您的代码中缺少的另一件事是:app.UseAuthentication();
  • 是的!这样做。我需要同时添加 app.UseAuthentication();和 app.UseAuthorization(); (按特定顺序)在 StartUp 上进行配置并开始工作!谢谢
  • app.UseAuthentication()的诡计;和 app.UseAuthorization();按这个顺序确实救了我的命!
猜你喜欢
  • 2020-02-11
  • 2019-01-04
  • 2017-06-20
  • 2020-03-28
  • 2020-12-17
  • 2020-03-04
  • 2017-10-18
  • 2019-08-05
  • 1970-01-01
相关资源
最近更新 更多