Search code examples
c#jwtasp.net-core-webapiasp.net-core-identity

.NET Core Web API HttpContext.User.Claims and HttpContext.User.Identity are always null in Controllers


I am using an ASP.NET Core Web API for the back-end and using JWT token in httpClient's header of a Blazor WASM client (I don't store JWT tokens in a cookie).

The problem is that although the user is logged in and the authentication and authorization works with no problems, but in every controller (inherited from ControllerBase) always:

  • HttpContext.User.Identity.IsAuthenticated is false
  • HttpContext.User.Identity.Name is null
  • HttpContext.User.Claims is null

But the request has the JWT token (Request.Headers["Authorization"][0] is equal to Bearer eyJhbGciOiJIUzI1...) and [Authorize] attribute works correctly.

This is how my startup.cs looks like:

services.AddIdentity()
            
services.AddSingleton<IAuthorizationPolicyProvider, AuthorizeExPolicyProvider>();

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                              options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(Configuration["jwt:key"])),
                    ClockSkew = TimeSpan.Zero
                });

services.AddAuthorization(options =>
            {
            });

And I also called the middleware in the right order :

app.UseRouting();

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

app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

Solution

  • HttpContext.User is only set when you have authentication for the method enabled.

    You can enable it by setting [Authorize] on your controller or action, or configure a global filter so all requests are authorized by default.