jwt npm
$ npm install jsonwebtoken
jwt npm
$ npm install jsonwebtoken
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) => {
// Get credentials from JSON body
const { username, password } = req.body
if (!username || !password || users[username] !== password) {
// return 401 error is username or password doesn't exist, or if password does
// not match the password in our records
return res.status(401).end()
}
// Create a new token with the username in the payload
// and which expires 300 seconds after issue
const token = jwt.sign({ username }, jwtKey, {
algorithm: "HS256",
expiresIn: jwtExpirySeconds,
})
console.log("token:", token)
// set the cookie as the token string, with a similar max age as the token
// here, the max age is in milliseconds, so we multiply by 1000
res.cookie("token", token, { maxAge: jwtExpirySeconds * 1000 })
res.end()
}
express jwt
// JWT MIDDLEWARE
const jwt = require('jsonwebtoken')
const httpError = require('http-errors')
module.exports = (req, res, next) => {
try {
const tokenHeader = req.headers.authorization.split('Bearer ')[1]
const decoded = jwt.verify(tokenHeader, process.env.ACCESS_TOKEN_SECRET)
req.user = decoded
next()
} catch (err) {
next(httpError(401))
}
}
// ROUTE LOGIN
app.get('/protect', authJwt, (req, res) => {
console.log(req.user)
res.send('aim in proteced route')
})
app.post('/login', (req, res) => {
const bodyPayload = {
id: Date.now(),
username: req.body.username
}
const token = signAccessToken(res, bodyPayload)
return res.status(200).json(token)
})
app.post('/refresh-token', (req, res) => {
const refreshToken = signRefreshToken(req)
res.status(200).json(refreshToken)
res.end()
})
// JWT HELPER
const jwt = require('jsonwebtoken')
const httpError = require('http-errors')
exports.signAccessToken = (res, payload) => {
try {
if (payload) {
const accessToken = jwt.sign({ ...payload }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1m' })
const refreshToken = jwt.sign({ ...payload }, process.env.REFRESH_TOKEN_SECRET, { expiresIn: '90d' })
res.cookie('refreshToken', `${refreshToken}`, { expired: 86400 * 90 })
return { accessToken, refreshToken }
}
} catch (err) {
return httpError(500, err)
}
}
exports.signRefreshToken = (req) => {
try {
const getToken = req.cookies.refreshToken
if (getToken) {
const { id, username } = jwt.verify(getToken, process.env.REFRESH_TOKEN_SECRET)
const accesssToken = jwt.sign({ id, username }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1m' })
return { accesssToken }
}
} catch (err) {
return httpError(401, err)
}
}
npm package for jwt
$ npm install jwt-simple
jsonwebtoken
RSASHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
,
)
jsonwebtoken
jwt.sign({ exp: Math.floor(Date.now() / 1000) + (60 * 60), data: 'foobar'}, 'secret');
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us