检查ASP.NET Core WebAPI JWT身份验证中是否存在用户



我已经成功地在我的WebAPI中设置了JWT身份验证/授权,但有一个问题:我可以创建一个新的用户帐户,生成它的JWT令牌,然后在令牌仍然有效时删除该帐户。在授权之前,我应该如何以及在哪里检查与令牌关联的用户是否确实存在

这是我设置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
};
});

我在控制器上使用[Authorize]属性,用户ID在JWT令牌中。

提前感谢!

您还可以在AddJwtBearer事件中验证用户:

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;
},
};

如果您想在该事件中检查数据库,您可以使用依赖项注入来获取数据库上下文,如:

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

最新更新