使用 jwt 授权在 Asp.net core 中检查用户验证 [英] check user validation in Asp.net core with jwt authorization

查看:39
本文介绍了使用 jwt 授权在 Asp.net core 中检查用户验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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. 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?

推荐答案

一个选项是在 JwtBearerEvent OnTokenValidated 事件上验证当前用户,该事件将在每次成功验证后触发

One option is to validate the current user on the JwtBearerEvent OnTokenValidated event which will be triggered after every successful authentication

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 方法,该方法将对您的用户提供程序实现进行操作.

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. Initialized as ServiceProvider = services.BuildServiceProvider(); in the ConfigureServices method. The IUserService is a wrapper class where you need to implement the IsUserRemoved method which will operate on your user provider implementation.

这篇关于使用 jwt 授权在 Asp.net core 中检查用户验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆