Authentication 检查ASP.NET核心WebAPI JWT身份验证中是否存在用户
我已经成功地在我的WebAPI中设置了JWT身份验证/授权,但有一个问题:我可以创建一个新的用户帐户,生成它的JWT令牌,然后在令牌仍然有效时删除该帐户。 授权前,我应该如何以及在何处检查与令牌关联的用户是否确实存在? 下面是我设置JWT的代码(Authentication 检查ASP.NET核心WebAPI JWT身份验证中是否存在用户,authentication,asp.net-core,jwt,authorization,asp.net-core-webapi,Authentication,Asp.net Core,Jwt,Authorization,Asp.net Core Webapi,我已经成功地在我的WebAPI中设置了JWT身份验证/授权,但有一个问题:我可以创建一个新的用户帐户,生成它的JWT令牌,然后在令牌仍然有效时删除该帐户。 授权前,我应该如何以及在何处检查与令牌关联的用户是否确实存在? 下面是我设置JWT的代码(Startup.cs): var secretKey=Configuration.GetValue(“secretKey”); var symmetricKey=new SymmetricSecurityKey(Encoding.UTF8.GetByte
Startup.cs
):
var secretKey=Configuration.GetValue(“secretKey”);
var symmetricKey=new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(选项=>
{
options.TokenValidationParameters=新的TokenValidationParameters()
{
validateisuer=true,
ValidateAudience=true,
ValidateSuersigningKey=true,
validisuser=“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>();
var dbcontext=context.HttpContext.RequestServices.GetRequiredService();
可能会有帮助:如果要在控制器之前检查,请使用IActionFilteraction@Mateech我已经调查过了,我知道我想检查用户是否存在,但是我不知道该在哪里做。如果你只想阻止客户端在其帐户被删除时访问,那么在删除之前未授权用户是另一种方法Hanks!这正是我要找的!