Advertisement
aldikhan13

EXAMPLE SIMPLE JWT REFRESH TOKEN

Nov 11th, 2020
335
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // JWT MIDDLEWARE
  2. const jwt = require('jsonwebtoken')
  3. const httpError = require('http-errors')
  4.  
  5. module.exports = (req, res, next) => {
  6.   try {
  7.     const tokenHeader = req.headers.authorization.split('Bearer ')[1]
  8.     const decoded = jwt.verify(tokenHeader, process.env.ACCESS_TOKEN_SECRET)
  9.     req.user = decoded
  10.     next()
  11.   } catch (err) {
  12.     next(httpError(401))
  13.   }
  14. }
  15.  
  16. // ROUTE LOGIN
  17. app.get('/protect', authJwt, (req, res) => {
  18.   console.log(req.user)
  19.   res.send('aim in proteced route')
  20. })
  21.  
  22. app.post('/login', (req, res) => {
  23.   const bodyPayload = {
  24.     id: Date.now(),
  25.     username: req.body.username
  26.   }
  27.   const token = signAccessToken(res, bodyPayload)
  28.   return res.status(200).json(token)
  29. })
  30.  
  31. app.post('/refresh-token', (req, res) => {
  32.   const refreshToken = signRefreshToken(req)
  33.   return res.status(200).json(refreshToken)
  34. })
  35.  
  36. // JWT HELPER
  37. const jwt = require('jsonwebtoken')
  38. const httpError = require('http-errors')
  39.  
  40. exports.signAccessToken = (res, payload) => {
  41.   try {
  42.     if (payload) {
  43.       const accessToken = jwt.sign({ ...payload }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1m' })
  44.       const refreshToken = jwt.sign({ ...payload }, process.env.REFRESH_TOKEN_SECRET, { expiresIn: '90d' })
  45.       res.cookie('refreshToken', `${refreshToken}`, { expired: 86400 * 90 })
  46.       return { accessToken, refreshToken }
  47.     }
  48.   } catch (err) {
  49.     return httpError(500, err)
  50.   }
  51. }
  52.  
  53. exports.signRefreshToken = (req) => {
  54.   try {
  55.     const getToken = req.cookies.refreshToken
  56.     if (getToken) {
  57.       const { id, username } = jwt.verify(getToken, process.env.REFRESH_TOKEN_SECRET)
  58.       const accesssToken = jwt.sign({ id, username }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1m' })
  59.       return { accesssToken }
  60.     }
  61.   } catch (err) {
  62.     return httpError(401, err)
  63.   }
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement