问题描述
我已使用 https://blogs.msdn.microsoft.com/webdev/2017/08/14/announcing-asp-net-core-2-0/(将目标框架更新为.NET Core 2.0,并使用元包Microsoft.AspNetCore.All).我也将所有可能的nuget软件包也更新为最新版本.
I have updated my project from Core 1.1 to Core 2.0 using instructions from https://blogs.msdn.microsoft.com/webdev/2017/08/14/announcing-asp-net-core-2-0/(updated target framework to .NET Core 2.0 and used metapackage Microsoft.AspNetCore.All). I have updated all possible nuget packages to latest versions as well.
在.NET Core 1.1中,我通过以下方式添加了JWT承载身份验证:
In .NET Core 1.1 i was adding JWT Bearer Authentication this way:
app.UseJwtBearerAuthentication(); // from Startup.Configure()
按照 http://www.talkingdotnet .com/whats-new-in-asp-net-core-2-0/对于Core 2.0,新方法是调用:
As per http://www.talkingdotnet.com/whats-new-in-asp-net-core-2-0/ for Core 2.0 the new way is to call:
services.AddJwtBearerAuthentication(); // from Startup.ConfigureServices()
但是没有方法 AddJwtBearerAuthentication().已安装软件包Microsoft.AspNetCore.Authentication.JwtBearer 2.0.0.
But the method AddJwtBearerAuthentication() is absent. The package Microsoft.AspNetCore.Authentication.JwtBearer 2.0.0 is installed.
新的空Core 2.0项目(带有JwtBearer程序包)也没有针对IServiceCollection的扩展方法AddJwtBearerAuthentication().
New empty Core 2.0 projects (with JwtBearer package) are also does not have extension method AddJwtBearerAuthentication() for IServiceCollection.
旧方法 app.UseJwtBearerAuthentication()根本无法编译:
Error CS0619 'JwtBearerAppBuilderExtensions.UseJwtBearerAuthentication(IApplicationBuilder, JwtBearerOptions)' is obsolete: 'See https://go.microsoft.com/fwlink/?linkid=845470'
请帮助.
推荐答案
在ConfigureServices中,使用以下代码来配置JWTBearer身份验证:
In ConfigureServices use the following code to configure JWTBearer Authentication:
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();
}
在UseMvc()
之前的Configure
中,添加UseAuthentication()
:
app.UseAuthentication();
app.UseStaticFiles();
app.UseMvc();
有关详细示例,请参见: https://github.com/aspnet/Security/blob/dev/samples/JwtBearerSample/Startup.cs#L51
For a detailed example see: https://github.com/aspnet/Security/blob/dev/samples/JwtBearerSample/Startup.cs#L51
这篇关于NET Core 2.0中缺少IServiceCollection的扩展方法AddJwtBearerAuthentication()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!