5

我已經使用來自https://blogs.msdn.microsoft.com/webdev/2017/08/14/announcing-asp-net-core-2-0/ (已更新的目標框架到.NET Core 2.0和已使用的元數據包Microsoft.AspNetCore.All)的指令從Core 1.1更新到Core 2.0。 。我已經將所有可能的nuget軟件包更新到最新版本。缺少擴展方法AddJwtBearerAuthentication()用於.NET Core 2.0中的IServiceCollection

在.NET核心1.1我被加入JWT承載認證是這樣的:

app.UseJwtBearerAuthentication(); // from Startup.Configure() 

作爲每http://www.talkingdotnet.com/whats-new-in-asp-net-core-2-0/爲核2.0的新方法是調用:

services.AddJwtBearerAuthentication(); // from Startup.ConfigureServices() 

但方法AddJwtBearerAuthentication ()不存在。封裝Microsoft.AspNetCore.Authentication.JwtBearer 2.0.0安裝。

新的空核2.0項目(JwtBearer包)也沒有用於IServiceCollection擴展方法AddJwtBearerAuthentication()。

老方法app.UseJwtBearerAuthentication()不會編譯所有:

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

請幫助。

回答

7

在ConfigureServices使用下面的代碼來配置JWTBearer認證:

public void ConfigureServices(IServiceCollection services) 
    { 
     services.AddAuthentication(o => 
     { 
      o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; 
      o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; 
     }).AddJwtBearer(o => 
     { 
      o.Authority = "https://localhost:54302"; 
      o.Audience = "your-api-id"; 
      o.RequireHttpsMetadata = false; 
     }); 

     services.AddMvc(); 
    } 

而且在Configure只是UseMvc()前添加UseAuthentication()

app.UseAuthentication(); 

app.UseStaticFiles(); 

app.UseMvc(); 

有關詳細示例,請參閱:https://github.com/aspnet/Security/blob/dev/samples/JwtBearerSample/Startup.cs#L51

0

方法:

// Configure authentication with JWT (Json Web Token). 
public void ConfigureJwtAuthService(IServiceCollection services) 
{ 
    // Enable the use of an [Authorize(AuthenticationSchemes = 
    // JwtBearerDefaults.AuthenticationScheme)] 
    // attribute on methods and classes to protect. 
    services.AddAuthentication().AddJwtBearer(cfg => 
    { 
    cfg.RequireHttpsMetadata = false; 
    cfg.SaveToken = true; 
    cfg.TokenValidationParameters = new TokenValidationParameters() 
    { 
     IssuerSigningKey = JwtController.SecurityKey, 
     ValidAudience = JwtController.Audience, 
     ValidIssuer = JwtController.Issuer, 
     // When receiving a token, check that we've signed it. 
     ValidateIssuerSigningKey = true, 
     // When receiving a token, check that it is still valid. 
     ValidateLifetime = true, 
     // This defines the maximum allowable clock skew when validating 
     // the lifetime. As we're creating the tokens locally and validating 
     // them on the same machines which should have synchronised time, 
     // this can be set to zero. 
     ClockSkew = TimeSpan.FromMinutes(0) 
    }; 
    }); 
} 

現在ConfigureServices()內的Startup.cs方法,你可以調用ConfigureJwtAuthService()方法配置JWT認證。