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 falseHttpContext.User.Identity.Name
is nullHttpContext.User.Claims
is nullBut 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();
});
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.