【发布时间】:2019-04-27 04:42:31
【问题描述】:
我正在尝试在核心 webapi 应用程序中使用 JWT。这是我的Startup.ConfigureServices():
services.AddDbContextPool("Bla Bla");
services.AddIdentity<IdentityUser, IdentityRole>("Bla Bla");
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication(o => {
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(c => {
c.RequireHttpsMetadata = false;
c.SaveToken = true;
c.TokenValidationParameters =
new TokenValidationParameters {
ValidIssuer = Configuration["JwtIssuer"],
ValidAudience = Configuration["JwtIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(Configuration["JwtKey"])),
ClockSkew = TimeSpan.Zero
};
});
services.AddRouting("Bla Bla");
services.AddMvcCore("Bla Bla").AddControllersAsServices();
这是Startup.Configure() 方法:
app.UseAuthentication();
app.UseMvc(rb =>
{ rb.MapRoute("api_default", "{controller}/{action}/{id?}"); });
无论如何,我已经创建了一个保护操作来测试(我希望它返回一个HTTP 401 Unauthorized 错误):
public class AccountController : ControllerBase {
[HttpGet]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public async Task<object> Info() {
return "Authorized!";
}
}
但它获得授权并响应“授权!”每时每刻。似乎Authorize 属性根本不起作用。我错过了什么吗?
附: [Authorize] 和 [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] 属性我都试过了。
P.S.2 我已经尝试从ControllerBase 和Controller 扩展控制器。
P.S.3 我尝试过不清除默认声明(删除了这一行 JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();)。
它们都不起作用。
框架和包信息:
- 目标框架:
netcoreapp2.1 -
Microsoft.AspNetCore版本 =2.1.6 -
Microsoft.AspNetCore.Authentication.JwtBearer版本 =2.1.2 -
Microsoft.AspNetCore.Identity.EntityFrameworkCore版本 =2.1.6 -
Microsoft.AspNetCore.Mvc.Core版本 =2.1.3
更新:
根据@sellotape's comment,我已经从action中返回了User对象:
[HttpGet]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public async Task<object> Info() {
return User;
}
这是输出 JSON:
{
"identities": [
{
"isAuthenticated": false,
"claims": [],
"roleClaimType": "http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
"nameClaimType": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"
}
],
"identity": {
"isAuthenticated": false,
"claims": [],
"roleClaimType": "http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
"nameClaimType": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"
},
"claims": []
}
【问题讨论】:
-
在该控制器操作中放置一个断点并检查用户声明和身份以查看经过身份验证的身份来自何处。这应该会提供一些线索...
-
@sellotape 没什么重要的。声明和身份是空的。查看更新以查看完整的
User对象。 -
我认为您在
ConfigureServices()中缺少services.AddAuthorization();... -
@sellotape 我添加了
services.AddAuthorization()但没有任何改变): -
谢谢;我现在已经添加了答案。
标签: c# authorization jwt asp.net-core-webapi netcoreapp2.1