Imran Khan
Imran Khan

Reputation: 2401

RESTful API using JWT (JSON Web Token) setup token expiry

I'm using JWT for RESTful API (Laravel Web-Services for mobile). How to setup token expiry to never expiry or what the best practice to setup token expiry? Because currently i need to get the token everytime when the token expired, can anybody have this issue or best solution for token expiry.

Upvotes: 2

Views: 2682

Answers (1)

Mina Abadir
Mina Abadir

Reputation: 2981

There is nothing to make the token never expire. However you can extend the expiration date to a very huge time span, 1 year for example. This is possible, however it is not recommended for security.

In order to achieve that, you need to configure two parts, the token refresh time, and token expiry.

So in config/jwt.php

'refresh_ttl' => 29030400,  // Number of minutes in 1 year (12*4*7*24*60*60)

And when you are creating your token, you can pass something like the following

$tokenId    = base64_encode(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
$issuedAt   = Carbon::now()->timestamp;
$notBefore  = $issuedAt;             //Adding 10 seconds
$expire     = $notBefore + 12*4*7*24*60*60;            // Adding 6 hours
    /*
    * Create the token as an array
    */
    $data = [
      'iat'  => $issuedAt,      // Issued at: time when the token was generated
      'jti'  => $tokenId,   // Json Token Id: an unique identifier for the token
      'iss'  => 'https://example.com',       // Issuer
      'nbf'  => $notBefore,        // Not before
      'exp'  => $expire,           // Expire
      'data' => [                  // Data related to the signed user
      'userId'   => Auth::user()->id, // userid from the users table
      ]
    ];

Now, your token will never expire before 1 year. And you have up to 1 year to refresh it. When the user opens the application the next time, and you authenticate the token, you can refresh it. You can refresh the token, as mentioned in the documentation here. I would recommend going through this laracasts discussion as well.

Also, I have found this question on StackOverflow, I think it will help.

Upvotes: 2

Related Questions