我已使用https://blogs.msdn.microsoft.com/webdev/2017/08/14/announcing-asp-net-core-2-0/中的说明将我的项目从Core 1.1更新到Core 2.0 (更新了.NET Core 2.0的目标框架并使用了元数据包Microsoft.AspNetCore.All)。我已将所有可能的nuget包更新到最新版本。
在.NET Core 1.1中,我以这种方式添加JWT承载认证:
app.UseJwtBearerAuthentication(); // from Startup.Configure()
根据Core {2.0的http://www.talkingdotnet.com/whats-new-in-asp-net-core-2-0/,新方法是调用:
services.AddJwtBearerAuthentication(); // from Startup.ConfigureServices()
但缺少方法 AddJwtBearerAuthentication()。已安装Microsoft.AspNetCore.Authentication.JwtBearer 2.0.0软件包。
新的空Core 2.0项目(使用JwtBearer包)也没有IServiceCollection的扩展方法AddJwtBearerAuthentication()。
旧方法 app.UseJwtBearerAuthentication()根本无法编译:
Error CS0619 'JwtBearerAppBuilderExtensions.UseJwtBearerAuthentication(IApplicationBuilder, JwtBearerOptions)' is obsolete: 'See https://go.microsoft.com/fwlink/?linkid=845470'
请帮忙。
答案 0 :(得分:9)
在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
答案 1 :(得分:0)
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.Audience = "http://localhost:5001/";
options.Authority = "http://localhost:5000/";
});
请参阅https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x
答案 2 :(得分:0)
配置Jwt身份验证的方法:
// 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)
};
});
}
现在,在 Startup.cs 的 ConfigureServices()方法中,您可以调用 ConfigureJwtAuthService()方法来配置Jwt身份验证。