简体   繁体   English

使用 jwt 授权在 Asp.net core 中检查用户验证

[英]check user validation in Asp.net core with jwt authorization

I implemented Microsoft Identity and JWT in my web api, a client can login and get a JWT token and store it in the application.我在我的 web api 中实现了 Microsoft Identity 和 JWT,客户端可以登录并获取 JWT 令牌并将其存储在应用程序中。 since the expiration of the token the user can access the the server, but if I remove a user from my database, the removed user still has its token and can access the web api, how can I check the validation of the user?由于令牌过期,用户可以访问服务器,但是如果我从我的数据库中删除一个用户,被删除的用户仍然拥有它的令牌并且可以访问 web api,我如何检查用户的验证?

One option is to validate the current user on the JwtBearerEvent OnTokenValidated event which will be triggered after every successful authentication一种选择是在 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;
                }
            };
        });

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.注意:在本例中,我使用 ServiceProvider 来获取 IUserService 的一个实例,该实例作为参数存储在 Startup.cs 类中。 Initialized as ServiceProvider = services.BuildServiceProvider();初始化为ServiceProvider = services.BuildServiceProvider(); in the ConfigureServices method.在 ConfigureServices 方法中。 The IUserService is a wrapper class where you need to implement the IsUserRemoved method which will operate on your user provider implementation. IUserService 是一个包装类,您需要在其中实现 IsUserRemoved 方法,该方法将对您的用户提供程序实现进行操作。

Another option is to implement and register your own SecurityTokenValidator .另一种选择是实现和注册您自己的SecurityTokenValidator To do so you need to create a class implemented ISecurityTokenValidator interface:为此,您需要创建一个实现ISecurityTokenValidator接口的类:

//using Microsoft.IdentityModel.Tokens

public class CustomValidator : ISecurityTokenValidator
{
   //interface implementation
   ...
}

and register it as an additional token validator via JwtBearerOptions.SecurityTokenValidators property :并通过JwtBearerOptions.SecurityTokenValidators属性将其注册为额外的令牌验证器:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer( options => {

        options.SecurityTokenValidators.Add(new CustomValidator()) 
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM