kwyntes
kwyntes

Reputation: 1302

Check if user exists in ASP.NET Core WebAPI JWT Authentication

I have succesfully setup JWT authentication/authorization in my WebAPI, but there's one problem: I can create a new user account, generate it's JWT token, then delete the account while the token is still valid. How and where should I check if the user associated with the token actually exists before authorizing?

Here's my code to setup JWT (Startup.cs):

var secretKey = Configuration.GetValue<string>("SecretKey");
            var symmetricKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateIssuerSigningKey = true,

                        ValidIssuer = "localhost",
                        ValidAudience = "localhost",
                        IssuerSigningKey = symmetricKey
                    };
                });

I'm using the [Authorize] attribute on my controllers and the user ID is in the JWT token.

Thanks in advance!

Upvotes: 4

Views: 2971

Answers (1)

Nan Yu
Nan Yu

Reputation: 27538

You can also validate the user in AddJwtBearer events :

options.Events = new JwtBearerEvents()
{
    OnTokenValidated = context =>
    {
        //get userid if type is "userid"
        var userid = context.Principal.Claims.Where(x => x.Type == "userid").FirstOrDefault().Value;
        if (true )
        {
            context.Fail("invaild token");
        }
        return Task.CompletedTask;
    },

};

If you want to check database in that event , you can use dependency inject to get db context like :

var dbcontext = context.HttpContext.RequestServices.GetRequiredService<ApplicationDbContext>();

Upvotes: 11

Related Questions