检查用户是否存在于 ASP.NET 核心 WebAPI JWT 身份验证中
Check if user exists in ASP.NET Core WebAPI JWT Authentication
我已经在我的 WebAPI 中成功设置了 JWT authentication/authorization,但是有一个问题:我可以创建一个新的用户帐户,生成它的 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>();
我已经在我的 WebAPI 中成功设置了 JWT authentication/authorization,但是有一个问题:我可以创建一个新的用户帐户,生成它的 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>();