【问题标题】:Check if user exists in ASP.NET Core WebAPI JWT Authentication检查用户是否存在于 ASP.NET Core WebAPI JWT 身份验证中
【发布时间】:2020-08-05 20:54:39
【问题描述】:

我已成功在我的 WebAPI 中设置 JWT 身份验证/授权,但有一个问题:我可以创建一个新用户帐户,生成它的 JWT 令牌,然后在令牌仍然有效时删除该帐户。 在授权之前我应该​​如何以及在哪里检查与令牌关联的用户是否确实存在?

这是我设置 JWT 的代码 (Startup.cs):

var secretKey = Configuration.GetValue<string>("SecretKey");
            var symmetricKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateIssuerSigningKey = true,

                        ValidIssuer = "localhost",
                        ValidAudience = "localhost",
                        IssuerSigningKey = symmetricKey
                    };
                });

我在我的控制器上使用[Authorize] 属性,并且用户 ID 在 JWT 令牌中。

提前致谢!

【问题讨论】:

  • 如果您想在控制器动作之前检查,请使用 IActionFilter
  • @Mateech 我已经调查过了,我知道我想检查用户是否存在,但我不知道在哪里做。
  • 如果您只想阻止客户在其帐户被删除时访问,则在删除之前取消对用户的授权是另一种方法

标签: authentication asp.net-core jwt authorization asp.net-core-webapi


【解决方案1】:

您还可以在AddJwtBearer 事件中验证用户:

options.Events = new JwtBearerEvents()
{
    OnTokenValidated = context =>
    {
        //get userid if type is "userid"
        var userid = context.Principal.Claims.Where(x => x.Type == "userid").FirstOrDefault().Value;
        if (true )
        {
            context.Fail("invaild token");
        }
        return Task.CompletedTask;
    },

};

如果你想在那个事件中检查数据库,你可以使用依赖注入来获取数据库上下文:

var dbcontext = context.HttpContext.RequestServices.GetRequiredService<ApplicationDbContext>();

【讨论】:

  • 谢谢!这正是我想要的!
猜你喜欢
  • 2018-09-02
  • 2019-09-06
  • 2021-04-20
  • 2017-05-10
  • 1970-01-01
  • 2019-07-17
  • 2019-05-19
  • 2018-07-08
  • 2018-05-30
相关资源
最近更新 更多