[英]check user validation in Asp.net core with jwt authorization
我在我的 web api 中实现了 Microsoft Identity 和 JWT,客户端可以登录并获取 JWT 令牌并将其存储在应用程序中。 由于令牌过期,用户可以访问服务器,但是如果我从我的数据库中删除一个用户,被删除的用户仍然拥有它的令牌并且可以访问 web api,我如何检查用户的验证?
一种选择是在 JwtBearerEvent OnTokenValidated 事件上验证当前用户,该事件将在每次成功认证后触发
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
var userService = ServiceProvider.GetService<IUserService>();
if(userService.IsUserRemoved(context.Principal.Identity.Name))
context.Fail("User is removed");
return Task.CompletedTask;
}
};
});
注意:在本例中,我使用 ServiceProvider 来获取 IUserService 的一个实例,该实例作为参数存储在 Startup.cs 类中。 初始化为ServiceProvider = services.BuildServiceProvider();
在 ConfigureServices 方法中。 IUserService 是一个包装类,您需要在其中实现 IsUserRemoved 方法,该方法将对您的用户提供程序实现进行操作。
另一种选择是实现和注册您自己的SecurityTokenValidator
。 为此,您需要创建一个实现ISecurityTokenValidator
接口的类:
//using Microsoft.IdentityModel.Tokens
public class CustomValidator : ISecurityTokenValidator
{
//interface implementation
...
}
并通过JwtBearerOptions.SecurityTokenValidators
属性将其注册为额外的令牌验证器:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer( options => {
options.SecurityTokenValidators.Add(new CustomValidator())
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.