|
I'm Building Node.js application and want to add auth using using JWT.How to verify tokens in Express. |
Replies: 2 comments
|
You can implement JWT authentication in Express.js using the jsonwebtoken package. Steps:
const token = jwt.sign({ userId: user._id }, 'secretKey', {
if (!token) return res.status(403).send('Token required'); jwt.verify(token, 'secretKey', (err, decoded) => {
This setup helps secure your API using JWT authentication. |
|
Implementation of JWT authentication using jsonwebtoken can be done in 2 ways:
It is recommended to use cookies to store the token, because the browser handles it automatically and it is more secure compared to localStorage — as JavaScript cannot access an httpOnly cookie, making it resistant to XSS attacks. // Generate token // Store in cookie // Verify token middleware if (!token) return res.status(401).json({ message: "Unauthorized" }); // Decode and attach user next(); export default verifyToken; // Protected route This approach is more secure and reliable, as the browser automatically sends the cookie with every request — eliminating the need to manually pass the token in headers. |
You can implement JWT authentication in Express.js using the jsonwebtoken package.
Steps:
Install the package:
npm install jsonwebtoken
Generate a token during login:
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: user._id }, 'secretKey', {
expiresIn: '1h'
});
const verifyToken = (req, res, next) => {
const token = req.headers['authorization'];
if (!token) return res.status(403).send('Token required');
jwt.verify(token, 'secretKey', (err, decoded) => {
if (err) return res.status(401).send('Invalid token');
req.user = decoded;
next();
});
};
app.get('/profile', verifyToken, (req, res) => {
…