Cannot access JWT claims from ASP.NET HttpContext

Viewed 796

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?

4 Answers

This is what I use to get the user name from 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;
    }
}

and call that like this:

Helper.GetUserName(HttpContext.User);

link to my repo containing above code

Try this:

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

Then:

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

and it must work.

You should add UseAuthorization() middleware after UseAuthentication() middleware

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

Your `Configure' method should be like this

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");
        });
    });
}
Related