C#C
C#3y ago
v0fbu1vm

❔ Will this operation be expensive or not?

During a request, I'm checking whether a user is currently suspended or not. So during each request I'm hitting the database and getting the user
builder.Services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.SaveToken = true;
                options.RequireHttpsMetadata = false;
                options.Events = new JwtBearerEvents
                {
                    OnTokenValidated = async context =>
                    {
                        var claimsPrincipal = context.Principal;
                        if (claimsPrincipal == null)
                        {
                            context.Fail("Access denied");
                            return;
                        }

                        var claim = claimsPrincipal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
                        if (string.IsNullOrEmpty(claim) || !Guid.TryParse(claim, out _))
                        {
                            context.Fail("Access denied.");
                            return;
                        }
                        
                        var userManager = context.HttpContext.RequestServices.GetRequiredService<UserManager<User>>();
                        var user = await userManager.FindByIdAsync(claim);

                        if (user == null || user.IsSuspended)
                        {
                            context.Fail("Access denied.");
                        }
                    }
                };
It just feel like this is not the right way?
Was this page helpful?