简体   繁体   中英

JWT Authentication wrong parameters

I'm learning how to add JWT token authentication to my webApi. This what I have done so far inside 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();
}

But I'm getting errors like:

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

and

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

You can do this in the ConfigureServices method in 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...
}

Then in Configure method:

app.UseAuthentication();

Try to do it in ConfigureService rather than Configure, try something like

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

It will work!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM