0

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?

Rajeev Menon
  • 284
  • 5
  • 16
  • 2
    There might be an explanation: The service is injected via the constructor in the Middleware, but the middleware is registered as a singleton (per application lifetime). You can inject you service via the Invoke method from the Middleware. Look on how MyMiddleware looks here: https://blog.dudak.me/2014/custom-middleware-with-dependency-injection-in-asp-net-core/ – Cristian-Ștefăniță Scăueru Dec 10 '22 at 15:46
  • @Cristian-ȘtefănițăScăueru You are spot on, based on your comments I did some research and found this page https://stackoverflow.com/questions/55449036/what-is-the-meaning-of-when-using-a-scoped-service-inject-the-service-into-the – Rajeev Menon Dec 10 '22 at 15:54

0 Answers0