In this tutorial, we are going to implement JWT (JSON Web Token) authentication in an Express.js application. Understanding how to secure your web application by implementing JWT Authentication is a vital skill for any developer.
By the end of this tutorial, you will learn:
- What JWT is and why it is used
- How to generate and verify JWTs
- How to secure your Express.js endpoints using JWT
Prerequisites
In JWT Authentication, when the user logs in using their credentials, a JWT is returned. Subsequent requests to the API require this JWT. The server then verifies the JWT sent in the header of the request and if it's valid, processes the request.
We are going to use the jsonwebtoken
npm package for this tutorial.
Step 1: Install the necessary packages.
npm install express jsonwebtoken
Step 2: Setup a basic Express.js server
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.json({
message: 'Welcome to the API'
});
});
app.listen(3000, () => console.log('Server started on port 3000'));
const jwt = require('jsonwebtoken');
app.post('/login', (req, res) => {
// Mock user
const user = { id: 3 };
const token = jwt.sign({ user }, 'your-unique-secret-key');
res.json({
token
});
});
In the code above, the jsonwebtoken
is used to sign the user object with a unique secret key. The resulting token
is then sent in the response.
function ensureToken(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('/protected', ensureToken, (req, res) => {
jwt.verify(req.token, 'your-unique-secret-key', (err, data) => {
if (err) {
res.sendStatus(403);
} else {
res.json({
message: 'Protected information. Congrats!',
data
});
}
});
});
In the above code, ensureToken
middleware function checks if there is a token in the authorization header. If not, it sends a 403 status (Forbidden). If there is a token, it's extracted and the request is passed to the next middleware. The '/protected' route is now secured by JWT.
In this tutorial, you learned about:
Next, you should try implementing JWT Authentication in a full-fledged application. You can explore adding roles to users, restricting access based on roles, and refreshing tokens.
Exercise 1: Create a '/logout' endpoint that invalidates the JWT.
Exercise 2: Try to implement role-based authorization using JWT.
Exercise 3: Research how to handle token expiration and implement token refreshing.
Remember, practice is key to mastering any concept. Happy coding!