locked
Reject a jwt token if the user is disabled in the database RRS feed

  • Question

  • User-585144208 posted

    I use jwt token in my asp.net core app and I have two issues. First, I wan to check each time the token is validated and see if the user is still active in database. I know there is OnMessageReceived event in JwtBearerEvents, but I do not know if I have to do the token validation manually or not and then extract the user id from it and validate it by calling the database. 

    At the moment when I generate jwt token, I add user id to claims and I know that I can extract it as below : 

     var token = httpRequest.Headers["Authorization"].FirstOrDefault().Split(' ')[1];
                var jwtToken = handler.ReadToken(token) as JwtSecurityToken;
    
                SecurityToken validatedToken;
                var principal = handler.ValidateToken(token, jwtTokenValidator.GetValidationParameters(), out validatedToken);
    
                if (validatedToken.ValidTo >= DateTime.Now)
                {
                    if (principal.Claims.Any(c => c.Type == "id"))
                    {
                        return Guid.Parse(principal.Claims.First(c => c.Type == "id").Value.ToString());
                    }
                }

    By the way, I do not know how can I use "OnMessageReceived " to check the user status in the database each time the token is being validated. 

    Thursday, March 26, 2020 1:48 PM

All replies

  • User711641945 posted

    Hi b.dev,

    You could reject jwt token in JwtBearer middleware like below:

    .AddJwtBearer(o =>
        {
            o.Events = new JwtBearerEvents
            {
                OnTokenValidated = async ctx =>
                {               
                    //Get EF context
                    var db = ctx.HttpContext.RequestServices.GetRequiredService<AuthorizationDbContext>();
    
                    //Check if user is disabled
                    //do your stuff...
                    bool userActive = ....
                    if (userActive )
                    {
                        //Add claim if yes                   
                    }
                }
            };
        });

    Reference:

    https://joonasw.net/view/adding-custom-claims-aspnet-core-2

    Best Regards,

    Rena

    Friday, March 27, 2020 8:46 AM
  • User-2054057000 posted

    There is another approach to work out this thing. In your API you check the claims to find out the User Info (eg credentials) then check them in the database to see if your user is disabled. If it is disabled then simply send unauthorized.

    [HttpPost]
    public IActionResult Post([FromBody] UserInfo user)
    {
    // check if user is disabled then send (Unauthorized()) else return OK if (!Authenticate()) return Unauthorized(); return Ok(information)); }

    Refer: How to secure APIs with JWT in ASP.NET Core 3.1 


     

    Thursday, April 2, 2020 5:38 AM