在我的 Asp.Net core Web api 中,我使用 Identity 和 Jwt 承载身份验证。它工作得很顺利,没有任何麻烦。这是代码,
配置服务():
services.AddIdentity<ApplicationUser, IdentityRole<int>>()
.AddEntityFrameworkStores<DataContext, int>()
.AddDefaultTokenProviders();
配置():
app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = "localhost:4200",
ValidAudience = "localhost:4200",
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SuperSecretKey_GetThisFromAppSettings")),
ValidateLifetime = true
}
});
今天我升级到了.net core 2.0 和整个技术栈。从可用的有限帮助中,我修改了这样的代码..
配置服务()
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<DataContext>()
.AddDefaultTokenProviders();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "localhost:4200";
options.Audience = "localhost:4200";
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateLifetime = true,
ValidIssuer = "localhost:4200",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SuperSecretKey_GetThisFromAppSettings"))
};
});
配置()
app.UseAuthentication();
现在身份验证不起作用。看起来它的内部配置为使用 Cookie 身份验证。
还有人遇到过这种情况吗?非常感谢对此的任何帮助!
谢谢
最佳答案
如果我从 MS 网站理解正确的话
https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x
Identity 添加 cookie 并将默认身份验证设置为 cookie 方案。 尝试改变你的
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
至
services.AddAuthentication(o => {
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
关于asp.net - Dotnet core 2.0 使用身份与 JwtBearer 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45904955/