JSON Web Tokens (JWT) is an open standard (RFC 7519) that defines a compact, self-contained 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.
When building APIs in NodeJS, JWT plays a crucial role in authentication and authorization. It allows users to authenticate, and once authenticated, they receive a JWT. This token is then used to authorize the user to access routes, services and resources that are allowed with this token. This makes JWT an indispensable tool for building secure APIs.
Implementing JWT in NodeJS is pretty straightforward, thanks to packages like jsonwebtoken. To get started, you need to install the jsonwebtoken package using npm.
npm install jsonwebtoken
Once installed, you can import the package into your file and start using it to create and verify tokens.
const jwt = require('jsonwebtoken');
To create a token, you use the sign() method. This method accepts three arguments: the payload, the secret, and the options. The payload is the object that contains the claims. Claims are statements about an entity (usually the user) and additional information. The secret is the secret key used to sign the token. Options are used to set other properties of the token, such as the signature algorithm and token expiration.
let payload = {username: 'user'};
let secret = 'somesecretkey';
let token = jwt.sign(payload, secret, {expiresIn: '1h'});
To verify a token, you use the verify() method. This method accepts three arguments: the token, the secret, and a callback function. The callback function is called with the verification result.
jwt.verify(token, secret, function(err, decoded) {
if (err) {
console.log('Token verification failed');
} else {
console.log('Token verified successfully');
}
});
An important thing to note is that you should always protect the secret used to sign the token. If someone has access to your secret, they can sign tokens themselves, which can lead to serious security issues.
In addition, you should always verify the token before allowing the user to access protected routes, services, or resources. This can be done using middleware that verifies the token on every request.
function authenticateToken(req, res, next) {
const token = req.headers['authorization'];
if (token == null) return res.sendStatus(401);
jwt.verify(token, secret, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
In summary, JWT is a powerful tool for authentication and authorization in NodeJS APIs. It allows you to create tokens that can be used to authenticate users and authorize them to access routes, services and resources. Implementing JWT in NodeJS is simple thanks to packages like jsonwebtoken.