使用 jwt 授权检查 Asp.net 核心中的用户验证
check user validation in Asp.net core with jwt authorization
我在我的网站中实施了 Microsoft Identity 和 JWT api,
客户端可以登录并获取 JWT 令牌并将其存储在应用程序中。
由于令牌过期用户可以访问服务器,
但是如果我从我的数据库中删除一个用户,被删除的用户仍然有它的令牌并且可以访问网络 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 class 中。在 ConfigureServices 方法中初始化为 ServiceProvider = services.BuildServiceProvider();
。 IUserService 是一个包装器 class,您需要在其中实现 IsUserRemoved 方法,该方法将在您的用户提供程序实现上运行。
另一种选择是实施和注册您自己的 SecurityTokenValidator
。为此,您需要创建一个 class 实现的 ISecurityTokenValidator
接口:
//using Microsoft.IdentityModel.Tokens
public class CustomValidator : ISecurityTokenValidator
{
//interface implementation
...
}
并通过 JwtBearerOptions.SecurityTokenValidators
property:
将其注册为附加令牌验证器
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer( options => {
options.SecurityTokenValidators.Add(new CustomValidator())
});
我在我的网站中实施了 Microsoft Identity 和 JWT api, 客户端可以登录并获取 JWT 令牌并将其存储在应用程序中。 由于令牌过期用户可以访问服务器, 但是如果我从我的数据库中删除一个用户,被删除的用户仍然有它的令牌并且可以访问网络 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 class 中。在 ConfigureServices 方法中初始化为 ServiceProvider = services.BuildServiceProvider();
。 IUserService 是一个包装器 class,您需要在其中实现 IsUserRemoved 方法,该方法将在您的用户提供程序实现上运行。
另一种选择是实施和注册您自己的 SecurityTokenValidator
。为此,您需要创建一个 class 实现的 ISecurityTokenValidator
接口:
//using Microsoft.IdentityModel.Tokens
public class CustomValidator : ISecurityTokenValidator
{
//interface implementation
...
}
并通过 JwtBearerOptions.SecurityTokenValidators
property:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer( options => {
options.SecurityTokenValidators.Add(new CustomValidator())
});