【发布时间】:2021-08-06 23:50:02
【问题描述】:
我试图从 ASP.NET Core 中的 Bearer 令牌访问用户的声明,但在处理程序中,HttpContext.User.Identity.Name 始终为空,Claims 集合为空。
令牌作为标头传递,如下所示:
授权:承载 eyJhbGci....
在Startup.Configure 中,我在UseRouting 之后和UseEndpoints 之前调用UseAuthentication。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync(context.User.Identity.Name ?? "null");
});
});
}
在Startup.ConfigureServices 我打电话给AddAuthentication 和AddJwtBearer。我添加了一堆选项来尝试尽可能多地禁用验证,因为我现在只是尝试从令牌中读取值,但这没有帮助。
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters {
ValidateIssuer = false,
ValidateIssuerSigningKey = false,
ValidateAudience = false,
ValidateActor = false,
ValidateLifetime = false,
ValidateTokenReplay = false,
};
}
);
}
我的令牌是来自https://jwt.io/#debugger-io 的默认虚拟令牌,解码后看起来像这样:
{"alg":"HS256","typ":"JWT"}{"sub":"1234567890","name":"John Doe","iat":1516239022}
为此我缺少什么?
【问题讨论】:
-
你有没有设置断点或者使用F12开发者工具查看响应,遇到401错误?我检查了你的 JWT 配置和令牌,它会在我这边显示 401 错误,但是如果我使用 Issuer 和 SigningKey 生成 JWT 令牌(检查this screenshot),并更改 JWT 配置like this,我可以得到来自 HttpContext 的用户信息。所以,你可以试试这个方法。
标签: c# asp.net asp.net-core