Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用jwt授权检查Asp.net核心中的用户验证_Asp.net_Asp.net Web Api_Asp.net Core_Asp.net Identity_Access Token - Fatal编程技术网

使用jwt授权检查Asp.net核心中的用户验证

使用jwt授权检查Asp.net核心中的用户验证,asp.net,asp.net-web-api,asp.net-core,asp.net-identity,access-token,Asp.net,Asp.net Web Api,Asp.net Core,Asp.net Identity,Access Token,我在web api中实现了Microsoft Identity和JWT, 客户端可以登录并获取JWT令牌,并将其存储在应用程序中。 由于令牌过期,用户可以访问服务器, 但是如果我从我的数据库中删除一个用户,删除的用户仍然有其令牌,并且可以访问web api, 如何检查用户的验证?一个选项是在JWTBeareEvent OnTokenValidated事件上验证当前用户,该事件将在每次成功验证后触发 services.AddAuthentication(JwtBearerDefaults.Auth

我在web api中实现了Microsoft Identity和JWT, 客户端可以登录并获取JWT令牌,并将其存储在应用程序中。 由于令牌过期,用户可以访问服务器, 但是如果我从我的数据库中删除一个用户,删除的用户仍然有其令牌,并且可以访问web api,
如何检查用户的验证?

一个选项是在JWTBeareEvent 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;
                }
            };
        });
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(选项=>{
options.Events=newjwtbearerevents
{
OnTokenValidated=上下文=>
{
var userService=ServiceProvider.GetService();
if(userService.IsUserRemoved(context.Principal.Identity.Name))
失败(“用户被删除”);
返回Task.CompletedTask;
}
};
});

注意:在本例中,我使用ServiceProvider获取IUserService的实例,该实例作为参数存储在Startup.cs类中。初始化为
ServiceProvider=services.BuildServiceProvider()。IUserService是一个包装类,您需要在其中实现IsUserRemoved方法,该方法将在您的用户提供程序实现上运行。

另一个选项是实现并注册您自己的
SecurityTokenValidator
。为此,您需要创建一个实现的类
ISecurityTokenValidator
接口:

//using Microsoft.IdentityModel.Tokens

public class CustomValidator : ISecurityTokenValidator
{
   //interface implementation
   ...
}
并通过以下方式将其注册为附加令牌验证器:


我照你说的做了。但是我的userService始终为空。@MSjjD好的,您是否已在像这样的配置服务中注册了它。AddTransient();现在它起作用了。谢谢@MSjjD太好了!如果这个答案有帮助的话,请接受/支持这个答案。这是一个错误
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer( options => {

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