18.10. Working with JSON Web Tokens (JWT) in NodeJS
JSON Web Tokens (JWT) is an open standard (RFC 7519) that defines a compact and 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.
JWT-based authentication is a popular way to authenticate web applications. With JWT authentication, a token is stored on the client, which is sent on each request to the server to be authenticated.
How to implement JWT-based authentication in a NodeJS API
To implement JWT-based authentication in a NodeJS API, you will need the following steps:
- Install jsonwebtoken package
- Create a login route to generate the token
- Verify token on every request
1. Install jsonwebtoken package
First, you'll need to install the jsonwebtoken package in your NodeJS project. You can do this using npm (Node Package Manager) with the following command:
npm install jsonwebtoken
2. Create a login route to generate the token
Next, you'll need to create a login route that will generate the JWT token. Here is an example of how you can do this:
const jwt = require('jsonwebtoken'); const express = require('express'); const app = express(); app.post('/login', (req, res) => { // Authenticate User const user = { id: 1, username: 'test', email: 'test@test.com' } jwt.sign({user: user}, 'secretkey', (err, token) => { res.json({ token: token }); }); });
In the example above, we authenticate the user first. We then use the jwt.sign function to create the JWT token. The jwt.sign function takes three parameters: the payload (in this case, the user object), the secret key, and a callback function.
3. Verify token on every request
Finally, you'll need to verify the JWT token on each request. You can do this by creating a middleware that verifies the token:
function authenticateToken(req, res, next) { const bearerHeader = req.headers['authorization']; if (typeof bearerHeader !== 'undefined') { const bearer = bearerHeader.split(' '); const bearerToken = bearer[1]; req.token = bearerToken; next(); } else { res.sendStatus(403); } } app.get('/api', authenticateToken, (req, res) => { jwt.verify(req.token, 'secretkey', (err, authData) => { if(err) { res.sendStatus(403); } else { res.json({ message: 'API accessed successfully', authDate }); } }); });
In the example above, the authenticateToken middleware checks whether the JWT token is present in the authorization header. If the token is present, it is verified using the jwt.verify function. If the token is valid, the request is allowed to proceed. If the token is not valid, an error status 403 (Forbidden) is sent.
And that's all you need to implement JWT-based authentication in a NodeJS API!