jwt auth refresh code example

Example 1: jwt refresh token

/**
@description for module commonjs
*/

// JWT MIDDLEWARE
const jwt = require('jsonwebtoken')
const { message } = require('../utils/util.message')
 
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)
  return res.status(200).json(refreshToken)
})
 
// JWT HELPER
const jwt = require('jsonwebtoken')
const { message } = require('../utils/util.message')
 
exports.signAccessToken = (res, payload) => {
  try {
    if (payload) {
      const accessToken = jwt.sign({ ...payload }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1d' })
      const refreshToken = jwt.sign({ ...payload }, process.env.REFRESH_TOKEN_SECRET, { expiresIn: '90d' })
      res.cookie('refreshToken', `${refreshToken}`, { maxAge: 86400 * 90, httpOnly: true })
      return { accessToken, refreshToken }
    }
  } catch (err) {
    message({
      response: res,
      statusCode: 401,
      method: req.method,
      message: 'Unautorization'
    })
  }
}
 
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: '90d' })
      return { accesssToken }
    }
  } catch (err) {
    message({
      response: res,
      statusCode: 401,
      method: req.method,
      message: 'Unautorization'
		})
  }
}

Example 2: jwt refresh token

/**
@description for module esm, change userDTO with your DTO
*/

import { Request, Response } from 'express'
import jwt, { Secret } from 'jsonwebtoken'
import { Base64 } from 'js-base64'
import { UsersDTO } from './../dto/users'
import { message } from '../utils/util.message'

const ACCESS_TOKEN_SECRET: Secret = process.env.ACCESS_TOKEN_SECRET
const REFRESH_TOKEN_SECRET: Secret = process.env.REFRESH_TOKEN_SECRET

export const signAccessToken = (res: Response, payload: UsersDTO): string | any => {
	try {
		if (payload) {
			const accessToken: string = jwt.sign({ ...payload }, ACCESS_TOKEN_SECRET, { expiresIn: '1d' })
			const refreshToken: string = jwt.sign({ ...payload }, REFRESH_TOKEN_SECRET, { expiresIn: '90d' })

			const encodedAccessToken: string = Base64.encode(accessToken)
			const encodedRefreshToken: string = Base64.encode(refreshToken)

			res.cookie('refreshToken', `${encodedRefreshToken}`, { maxAge: 86400 * 90, httpOnly: true })

			return { accessToken: encodedAccessToken, refreshToken: encodedRefreshToken }
		}
	} catch (err) {
		return message({
          response: res,
          statusCode: 401,
          method: req.method,
          message: 'Unautorization'
		})
	}
}

export const signRefreshToken = () => (req: Request): string | any => {
	try {
		const getToken: string = req.cookies['refreshToken']

		if (Base64.isValid(getToken) && getToken) {
			const decodedToken: string = Base64.decode(getToken)

			const { user_id, email }: string | any = jwt.verify(decodedToken, REFRESH_TOKEN_SECRET)
			const accessToken: string = jwt.sign({ user_id: user_id, email: email }, ACCESS_TOKEN_SECRET, {
				expiresIn: '90d'
			})

			const encodedAccessToken: string = Base64.encode(accessToken)
			return encodedAccessToken
		}
	} catch (err) {
		message({
          response: res,
          statusCode: 401,
          method: req.method,
          message: 'Unautorization'
		})
	}
}