I was running into strange user access issues which currently stands resolved. I have this scoped service as below.
services.AddScoped<IJwtService, JwtService>();
The following custom middleware, which has the above service DI through constructor.
app.UseMiddleware<AccessCheckToRoutesMiddleware>();
The following was the original code for the JwtService
public JwtService(IHttpContextAccessor httpContextAccessor)
{
this.httpContextAccessor = httpContextAccessor;
//Later removed this section of code below to make it work consistently
try
{
_identity = httpContextAccessor.HttpContext.User.Identity as ClaimsIdentity;
}
catch { }
}
private void _getIdentity()
{
if (_identity==null) _identity = httpContextAccessor.HttpContext.User.Identity as ClaimsIdentity;
//Later changed the above section of code as below to make it work consistently
_identity = httpContextAccessor.HttpContext.User.Identity as ClaimsIdentity;
}
public bool IsPrivilegedUser()
{
_getIdentity();
var val = _identity.FindFirst("IsPrivilegedUser")?.Value;
return val.Equals("True", StringComparison.OrdinalIgnoreCase);
}
As explained in the code above, if I don't store the httpContextAccessor.HttpContext.User.Identity into a variable and get it every time straight, it gives strange results (basically the claims gets mixed up between various users accessing the app at that time. Can somebody exlain what is going on here? Is this a thread safety issue or is it some type of caching issue?