首页 > 解决方案 > JWT Authentication 参数错误

问题描述

我正在学习如何将 JWT 令牌身份验证添加到我的 webApi。这是我到目前为止所做的Startup.cs

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
..
..
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   if (env.IsDevelopment())
   {
    app.UseDeveloperExceptionPage();
   }

   app.UseJwtBearerAuthentication(new JwtBearerOptions
   {
     AutomaticAuthenticate = true,

     TokenValidationParameters = new TokenValidationParameters
     {
        ValidIssuer = "http://localhost:Port",
        ValidateAudience = false,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("testPass"))
     }
   });

   app.UseMvc();
}

但我收到如下错误:

  1. JwtBearerAppBuilderExtensions.UseJwtBearerAuthentication(IApplicationBuilder, JwtBearerOptions)' is obsolete: 'See https://go.microsoft.com/fwlink/?linkid=845470

2. JwtBearerOptions' does not contain a definition for 'AutomaticAuthenticate'

标签: c#authenticationjwtasp.net-core-webapi

解决方案


您可以在 中的ConfigureServices方法中执行此操作StartUp.cs

  public void ConfigureServices(IServiceCollection services)
    {            
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
        {
            o.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = false,
                ValidateLifetime = false,
                ValidateIssuerSigningKey = true,

                ValidIssuer = "http://localhost:Port",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourKey")) 
            };
        });

    // other configuration...
}

然后在Configure方法中:

app.UseAuthentication();

推荐阅读