Node.js Authentication With JWT code example
Example 1: 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 2: nodejs authentication token
Setting up our development environment and initializing our express server.
Creating our first basic route and controller.
Fleshing out our routes and controllers to add users and login users.
Creating a route and controller that will handle getting all users.
Example 3: token authentication in nodejs
If the request contains the access token, then the server will verify whether it was issued by the server itself using the stored secret. In case the token is expired or recognized as a one not signed by the server, the jsonwebtoken’s verify method will throw an error. We can handle the error to return a 401 error back to the client.