JWT stands for JSON Web Token. It is an open standard (RFC 7519) that defines a simple and secure way for sharing information between two parties (generally client and server) as a JSON object. The information shared in JWT can be verified and trusted because it is digitally signed.
In modern day web application development using JavaScript, JWT are used in authentication systems, where the server creates a new JWT and share it with the client. And then the client uses the JWT to in each request that it sends to the backend so that the backend can verify each request that it receives from the client.
To set expiry time in JWT with jsonwebtoken package, you can do it like this,
jwt.sign({
data: 'foobar'
}, 'SECRET KEY', { expiresIn: '1h' });
or,
jwt.sign({
exp: Math.floor(Date.now() / 1000) + (60 * 60),
data: 'foobar'
}, 'SECRET KEY');
To set the expiry time to an year, you can use value 8760 hours that is 1 year.
If you don't provide the expiresIn
option or the exp
claim, then your JWT will never expire, and it's expiry will be set for maximum age. We don't recommend it.
To understand what we are doing in the code above, read the entire article.
Structure of a JWT
A JWT is made up of three parts:
-
Header: Contains metadata about the type of token and the algorithm used for signing it.
-
Payload: Contains the claims, which are statements about an entity (typically, the user) and additional data.
-
Signature: Ensures that the token hasn’t been altered. It is created using the header, payload, a secret, and the algorithm specified in the header.
These three parts are encoded in Base64Url and concatenated with periods to form a JWT, which looks like this:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
The Header of JWT looks like this,
{
"alg": "HS256",
"typ": "JWT"
}
And the Payload,
{
"user_id": "1234567890",
"user_name": "Abhishek Ahlawat",
"iat": 1516239022
}
This is a sample Payload where I have stored the user_id and the user_name in the JWT payload.
You can store anything you want in the JWT token, but never a password, or anything that you would want to keep secure. The JWT Payload should always have the general public information stored in it.
The iat field stores the issued at time in the form of timestamp.
Expiry Time in JWT
By default, if you don't set the expiry time for a JWT then your JWT will never expire. It is not something that we recommend, but if you create a JWT without providing any expiry time, then the token will never expire.
In JavaScript based backend, you can use the jsonwebtoken package to create a new JWT token.
Following is the syntax of the sign method that you can use to generate a new JWT:
jwt.sign(payload, secretOrPrivateKey, [options, callback])
Let's see an example,
var jwt = require('jsonwebtoken');
var token = jwt.sign({ foo: 'bar' }, 'SECRET KEY');
The object {foo: 'bar'}
is the data part, and you can add anything you want in here.
Backdate a JWT Token
If you want to backdate a JWT token, you can provide the iat value yourself. To back date the JWT token, you will have to provide a timestamp less than the current timestamp for past date time.
var jwt = require('jsonwebtoken');
var older_token = jwt.sign({ foo: 'bar', iat: Math.floor(Date.now() / 1000) - 30 }, 'SECRET KEY');
As you can see in the code above, we have specified the iat field with a value 30 seconds before the current time.
Set Expiry Time in JWT
Now let's see how we can add an expiry time to the JWT token. You can use the expiresIn
option while creating the JWT token.
For example,
jwt.sign({
data: 'foobar'
}, 'SECRET KEY', { expiresIn: '1h' });
You can also provide the value for expiresIn in different formats like "1d
" for one day, 60
, "2 days"
, "10h"
, "7d"
, etc. A numeric value is interpreted as a seconds count.
You can also use the exp
field to set the expiration claim for the token. Let's see an example,
jwt.sign({
exp: Math.floor(Date.now() / 1000) + (60 * 60),
data: 'foobar'
}, 'SECRET KEY');
So these are the two ways to expire a JWT or set expiry time in JWT.
End Note
We would recommend that you always add an expiry time to your JWT. If you do not add an expiry time to the JWT then your token will never expire which can be a security issue because if a token never expires then a hacker can get access to JWT for user accounts of your web application and then can access the user accounts because the token never expires.