更新时间:2023-02-14 15:35:10
一个选项是在 JwtBearerEvent OnTokenValidated 事件上验证当前用户,该事件将在每次成功验证后触发
One option is to validate the current user on the JwtBearerEvent OnTokenValidated event which will be triggered after every successful authentication
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 类中.在 ConfigureServices 方法中初始化为 ServiceProvider = services.BuildServiceProvider();
.IUserService 是一个包装类,您需要在其中实现 IsUserRemoved 方法,该方法将对您的用户提供程序实现进行操作.
Note: In this example I use ServiceProvider, to get the an instance of IUserService, which is stored in the Startup.cs class as a parameter. Initialized as ServiceProvider = services.BuildServiceProvider();
in the ConfigureServices method. The IUserService is a wrapper class where you need to implement the IsUserRemoved method which will operate on your user provider implementation.