I'm building a .NET8 web app with a REST API where I'm trying to check if the requesting user is an admin to execute different code paths based on that but for some reason the code which is supposed to check it always returns false.
The controller method:
[HttpPut][Route("api/vehicle")][SwaggerResponse((int)HttpStatusCode.Accepted)]public async Task<IActionResult> VehicleModify([FromBody] VehicleModel vehicleModel){ bool userIsAdmin = JwtMiddleware.IsUserInRoleForHttpContext(_httpContextAccessor, "Admin"); if (!userIsAdmin) { _logger.LogInformation("VehicleModify {@Plate}", vehicleModel.Plate); return Unauthorized(); } if (vehicleModel == null) return BadRequest(); await _vehicleService.Modify(vehicleModel); return Accepted();}
The IsUserInRoleForHttpContext()
method:
public static bool IsUserInRoleForHttpContext(IHttpContextAccessor httpContextAccessor, string roleName){ var user = httpContextAccessor.HttpContext?.User; if (user == null || !user.Identity.IsAuthenticated) // IsAuthenticated always false return false; return user.IsInRole(roleName);}
So apparently:
httpContextAccessor.HttpContext?.User.Identity.IsAuthenticated
is always false.
What am I doing wrong?