1

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?

2 Answers 2

2

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;
                }
            };
        });

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I did as you said. but my userService in always null.
@MSjjD ok, have you registered it in the ConfigureServices like this services.AddTransient<IUserService, UserService>();
now it works. thank you 🙏. context.Principal.Identity.Name returns null. I am using context.Principal.Claims.First().Value instead. I works. but I think Its not good.
@MSjjD great! Please accept/upvote answer this answer if it helped
Sry that was a mistake
|
0

Another option is to implement and register your own SecurityTokenValidator. To do so you need to create a class implemented ISecurityTokenValidator interface:

//using Microsoft.IdentityModel.Tokens

public class CustomValidator : ISecurityTokenValidator
{
   //interface implementation
   ...
}

and register it as an additional token validator via JwtBearerOptions.SecurityTokenValidators property:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer( options => {

        options.SecurityTokenValidators.Add(new CustomValidator()) 
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.