jwt authentication nodejs one token only code example
Example 1: jwt in node js
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
app.post('/login', (req, res) => {
const user = {
id: 1,
username: 'abhishek',
email: "[email protected]"
}
let token = jwt.sign({ user: user }, 'shhhhh');
res.send(token);
})
app.get('/api', verifyToken, (req, res) => {
try {
jwt.verify(req.token, 'shhhhh', (error, authData) => {
if (error) {
res.send("not logged in")
}
res.json({
message: "post Created",
authData
})
})
} catch (error) {
res.send(error)
}
})
function verifyToken(req, res, next) {
try {
const bearerHeader = req.headers['authorization'];
if (typeof bearerHeader !== 'undefined') {
const bearerToken = bearerHeader.split(' ')[1];
req.token = bearerToken;
next();
}
else {
res.send("Not logged-in")
}
}
catch {
res.send("something went wrong")
}
}
app.listen(3000, () => {
console.log("server is runing")
})
Example 2: jwt token example in node js
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
if (token == null) return res.sendStatus(401)
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET as string, (err: any, user: any) => {
console.log(err)
if (err) return res.sendStatus(403)
req.user = user
next()
})
}