3

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!

kwyntes
  • 1,045
  • 10
  • 27

1 Answers1

9

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>();
Nan Yu
  • 26,101
  • 9
  • 68
  • 148