jwt.sign node js example
Example 1: json web token npm
$ npm install jsonwebtoken
Example 2: jwt implementation in node js
const jwt = require("jsonwebtoken")
const jwtKey = "my_secret_key"
const jwtExpirySeconds = 300
const users = {
user1: "password1",
user2: "password2",
}
const signIn = (req, res) => {
const { username, password } = req.body
if (!username || !password || users[username] !== password) {
return res.status(401).end()
}
const token = jwt.sign({ username }, jwtKey, {
algorithm: "HS256",
expiresIn: jwtExpirySeconds,
})
console.log("token:", token)
res.cookie("token", token, { maxAge: jwtExpirySeconds * 1000 })
res.end()
}
Example 3: 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()
})
}
Example 4: npm package for jwt
$ npm install jwt-simple