check user validation in Asp.net core with jwt authorization

前端 未结 2 513
暗喜
暗喜 2021-01-16 03:15

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

2条回答
  •  情书的邮戳
    2021-01-16 03:57

    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();
                        if(userService.IsUserRemoved(context.Principal.Identity.Name))
                            context.Fail("User is removed");
    
                        return Task.CompletedTask;
                    }
                };
            });
    

    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.

提交回复
热议问题