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

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

问题描述

我在我的Web API中实现了Microsoft Identity和JWT,客户端可以登录并获取JWT令牌并将其存储在应用程序中.由于令牌到期,用户可以访问服务器,但是,如果我从数据库中删除了一个用户,那么被删除的用户仍然拥有其令牌,并且可以访问网络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核心中的用户验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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