I am trying to access a user's claims from his Bearer token in ASP.NET Core, but in the handler, HttpContext.User.Identity.Name
is always null, and the Claims
collection is empty.
The token is passed as a header like this:
Authorization: Bearer eyJhbGci....
In Startup.Configure
I call UseAuthentication
after UseRouting
and before UseEndpoints
.
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");
});
});
}
In Startup.ConfigureServices
I call AddAuthentication
and AddJwtBearer
. I added a bunch of options to try and disable as much validation as I could, as I'm just trying to read the values from the token for now, but that didn't help.
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,
};
}
);
}
My token is a default dummy one from https://jwt.io/#debugger-io and it looks like this when decoded:
{"alg":"HS256","typ":"JWT"}{"sub":"1234567890","name":"John Doe","iat":1516239022}
What am I missing for this to work?