无法从ASP.NET HttpContext访问JWT声明



我正试图从ASP.NET Core中的Bearer令牌访问用户的声明,但在处理程序中,HttpContext.User.Identity.Name始终为null,而Claims集合为空。

令牌以如下标头形式传递:

授权:Bearer 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中,我调用AddAuthenticationAddJwtBearer。我添加了一堆选项,试图尽可能多地禁用验证,因为我现在只是试图从令牌中读取值,但这没有帮助。

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}

我缺少什么才能让它发挥作用?

默认情况下,Name声明类型映射到UniqueName,您需要更改其映射。

.AddJwtBearer(o => o.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name"
})

请参考此问题:我可以使用JWT进行身份验证,但我的ASP.NET Core应用程序中无法识别我的Name声明

这是我用来从JWT:获取用户名的方法

public class Helper
{
/// <summary>
/// Retrieve name of the user executing the request.
/// </summary>
/// <param name="user">User info.</param>
/// <returns>User name.</returns>
internal static string GetUserName(ClaimsPrincipal user)
{
return user.Claims
.FirstOrDefault(c => c.Type == ClaimTypes.Name || c.Type == "name")
.Value;
}
}

并这样称呼它:

Helper.GetUserName(HttpContext.User);

链接到我的回购包含上述代码

试试这个:

services
.AddControllers(options =>
{
options.Filters.Add(new AuthorizeFilter());
});

然后:

app.UseAuthentication();
app.UseAuthorization(); 

它必须起作用。

您应该在UseAuthentication()中间件之后添加UseAuthorization()中间件

app.UseAuthentication();
app.UseAuthorization();

你的"配置"方法应该像这个

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync(context.User.Identity.Name ?? "null");
});
});
}

最新更新