How to sign a JSON Web Token?
Signing a JSON Web Token (JWT) is an essential process to guarantee the authenticity and integrity of data transferred in web applications. Using the jsonwebtoken
library, we can implement a signing system in three fundamental steps: define the payload, choose the appropriate algorithm and sign the token with a secret or private key. This implementation is crucial to protect your endpoints and ensure secure data communication.
What do we need to sign a JWT?
- Payload: It is the JSON object that contains the Claim Names, such as
sub
, name
and exp
. Using the verified user information is vital for its correct creation.
- Secret or Private Key: Depending on the signing algorithm:
- Symmetric (HS256): Uses a secret.
- Asymmetric (RS256): Uses a private key.
- Options or callback function: It can include additional configurations for the JWT.
Practical implementation in Node.js
Construction of the payload
Before proceeding to signing, it is vital to structure the payload correctly. Here is an example of how this could be done:
const user = ;const payload = { sub: user.id, name: user.full_name, exp: Math.floor(Date.now() / 1000) + (60 * 1) };
Signing the token
To sign the token, we first import the jsonwebtoken
library and then use the sign
method:
const jwt = require('jsonwebtoken');const secret = process.env.SECRET_KEY;
const token = jwt.sign(payload, secret);
Recommendations for handling the secret
- Make sure that the
secret
is a long random string.
- Use environment variables to store the
secret
and other sensitive data.
- Never expose your
secret
or private key in the repository.
Testing and verification in Postman
To verify that the server and endpoints are working properly, first verify access to the public endpoint:
- Make a request to
public
to confirm that the server is running.
- Request the endpoint
token
to obtain the signed JWT.
- Evaluate the received token by accessing the private endpoint.
Challenge for the reader: Implement in another language.
A great exercise would be to perform this same implementation of signing a JWT in another programming language other than Node.js. This will not only help you broaden your skills, but also help you understand the differences between implementations in different environments.
Go ahead and put your knowledge into practice, explore new languages and keep improving your skills in web application programming and security!
Want to see more contributions, questions and answers from the community?