Search code examples
jwt

How to programmatically check for JWT token expiration and logout user automatically?


I have this function that will create the token and it has expiry time:

private string CreateJWT(User user)
    {
        var secretKey = configuration.GetSection("AppSettings:Key").Value;
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));

        var claims = new Claim[] {
            new Claim(ClaimTypes.Name, user.Username),
            new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
        };

        var signingCredentials = new SigningCredentials(
                                key, SecurityAlgorithms.HmacSha256Signature);

        var tokenDescriptor = new SecurityTokenDescriptor{
            Subject = new ClaimsIdentity(claims),
            Expires = DateTime.UtcNow.AddMinutes(1),
            SigningCredentials = signingCredentials
        };

        var tokenHandler = new JwtSecurityTokenHandler();
        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    }

in login controller I am assigning the token:

loginRes.Token = CreateJWT(user);

now in my app how to check if the token is expired? If expired, how to log out the user without user interaction?

I have tried the following:

ngOnInit() {

this.token = localStorage.getItem("token");

if (this.token.expired !== true)
{
  localStorage.removeItem("token"); 
  this.router.navigate(["user/login"]);
}

the token.expired is undefined.


Solution

  • I found the solution by adding a timer to the event:

    this.token = localStorage.getItem("token");
    
    timer(0, 600000).subscribe(() => { 
    
      const parseJwt = (this.token);        
      const decode = JSON.parse(atob(this.token.split('.')[1]));
      console.log(decode);
      if (decode.exp * 1000 < new Date().getTime()) 
      {
        localStorage.removeItem('token');
        localStorage.removeItem('chosenfolder');
        localStorage.removeItem('userName');
        localStorage.removeItem('isAdmin');
        localStorage.removeItem('userId');
        this.router.navigate(["user/login"]);
        this.alertify.error("Session Expired!")
      }