【问题标题】:check user validation in Asp.net core with jwt authorization使用 jwt 授权检查 Asp.net 核心中的用户验证
【发布时间】:2018-09-10 04:27:30
【问题描述】:

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

【问题讨论】:

    标签: asp.net asp.net-web-api asp.net-core asp.net-identity access-token


    【解决方案1】:

    另一种选择是实现并注册您自己的SecurityTokenValidator。为此,您需要创建一个实现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()) 
        });
    

    【讨论】:

      【解决方案2】:

      一个选项是在 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 类中。在 ConfigureServices 方法中初始化为 ServiceProvider = services.BuildServiceProvider();。 IUserService 是一个包装类,您需要在其中实现 IsUserRemoved 方法,该方法将对您的用户提供程序实现进行操作。

      【讨论】:

      • 我照你说的做了。但我的 userService 始终为空。
      • @MSjjD 好的,你有没有像这样在 ConfigureServices 中注册 services.AddTransient();
      • 现在可以了。谢谢?。 context.Principal.Identity.Name 返回 null。我正在使用 context.Principal.Claims.First().Value 代替。我工作。但我认为它不好。
      • @MSjjD 太棒​​了!如果有帮助,请接受/支持回答此答案
      • 对不起,这是个错误
      猜你喜欢
      • 2020-09-10
      • 2017-05-13
      • 2019-03-07
      • 2020-02-16
      • 1970-01-01
      • 2018-02-20
      • 2018-11-10
      • 2019-04-21
      • 2020-04-28
      相关资源
      最近更新 更多