One of the most important topics we will cover in our e-book course 'How to create APIs in NodeJS from basics to advanced' is the use of JSON Web Tokens (JWT) in NodeJS. JWT is a secure way to pass information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.
The JWT consists of three parts: the header, the payload, and the signature. The header typically consists of the type of token and the signature algorithm used. The payload contains the claims or pieces of information being passed. The signature is used to verify that the sender of the JWT is who it claims to be and to ensure that the message has not been altered along the way.
One of the most crucial aspects of working with JWT is configuring token expiration. Expiring a token is important because it helps protect the application from potential security threats. Non-expiring tokens can be dangerous as if a malicious actor gets one, they will have continued access to the system.
In NodeJS, we can use the jsonwebtoken library to work with JWT. To install this library, you can use the npm command:
npm install jsonwebtoken
Once the library is installed, you can start using it to create and verify tokens. Here is an example of how to create a token with a defined expiration:
const jwt = require('jsonwebtoken'); const date = { id: 1, name: 'John Doe' }; const secret = 's3cr3t'; const token = jwt.sign(data, secret, { expiresIn: '1h' });
In this example, 'data' is the object we want to encode in the token. 'Secret' is the secret key that will be used to sign the token. The final object passed to the jwt.sign function is an options object. The 'expiresIn' option allows you to set the token expiration. In this case, the token will expire in one hour.
To verify a token, you can use the jwt.verify function. Here is an example:
const jwt = require('jsonwebtoken'); const token = '...'; // the token you received const secret = 's3cr3t'; try { const decoded = jwt.verify(token, secret); console.log(decoded); } catch (err) { console.error('Invalid token:', err); }
If the token is valid and has not expired, jwt.verify will return the decoded object. If the token is invalid or expired, it will throw an error.
It is important to note that you should always protect the secret key used to sign tokens. If a malicious actor gets your secret key, they can sign their own tokens and gain access to your system. Therefore, in a production environment, you should use a secret management solution to protect your keys.
Also, although JWTs are a convenient way to pass information between the client and the server, they should not be used to store sensitive information unless they are encrypted. This is because the contents of a JWT can be easily decoded and read by anyone who obtains the token.
In summary, JWTs are a powerful tool for authentication and authorization in NodeJS applications. They allow you to transmit information securely between parties and can be easily set to expire after a certain amount of time, helping to increase the security of your application.