how to refresh token code example

Example 1: 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'
		})
	}
}

Example 2: jwt refresh token

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

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, options: SignOptions): string | any => {
	if (!payload) {
		return null
	} else {
		const accessToken: string = jwt.sign({ ...payload }, ACCESS_TOKEN_SECRET, { ...options })
		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 }
	}
}

export const verifySignAccessToken = () => (token: string): string | any => {
	if (!Base64.isValid(token)) {
		return null
	} else {
		const decodedToken: string = Base64.decode(token)
		const decoded: string | any = jwt.verify(decodedToken, ACCESS_TOKEN_SECRET)
		return decoded
	}
}

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

	if (!Base64.isValid(getToken) && !getToken) {
		return null
	} else {
		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
	}
}

Example 3: Auto refresh token

Axios.interceptors.response.use(response => response, error => {
    const status = error.response ? error.response.status : null

    if (status === 401) {

        return refreshToken(store).then(_ => {
            error.config.headers['Authorization'] = 'Bearer ' + store.state.auth.token;
            error.config.baseURL = undefined;
            return Axios.request(error.config);
        });
    }

    return Promise.reject(error);
});

Example 4: Auto refresh token

function refreshToken(store) {
    if (store.state.auth.isRefreshing) {
        return store.state.auth.refreshingCall;
    }
    store.commit('auth/setRefreshingState', true);
    const refreshingCall = Axios.get('get token').then(({ data: { token } }) => {
        store.commit('auth/setToken', token)
        store.commit('auth/setRefreshingState', false);
        store.commit('auth/setRefreshingCall', undefined);
        return Promise.resolve(true);
    });
    store.commit('auth/setRefreshingCall', refreshingCall);
    return refreshingCall;
}