Skip to content

Instantly share code, notes, and snippets.

Last active August 13, 2020 18:59
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save zfael/ecb0402e4562deabbd9e6bb5b2bd58bc to your computer and use it in GitHub Desktop.
Node.js - refresh token approach with 2 way encryption + JWT
import crypto from 'crypto';
import jwt from 'jsonwebtoken';
import { v4 as uuid } from 'uuid';
const secret = 'your-access-token-secret';
console.log('access token secret\n', secret);
const refreshTokenSecret = 'your-refresh-token-secret';
console.log('refresh token secret\n', refreshTokenSecret);
const refreshTokenPayload = {
userId: '1',
console.log('\nrefresh token payload\n', refreshTokenPayload);
const algorithm = 'aes-192-cbc';
const iv = Buffer.alloc(16, 0);
const key = crypto.scryptSync(refreshTokenSecret, 'salt', 24);
const cipher = crypto.createCipheriv(algorithm, key, iv);
const data =
cipher.update(JSON.stringify(refreshTokenPayload), 'utf8', 'hex') +'hex');
console.log('refresh token payload encrypted\n', data);
const refreshToken = jwt.sign({ data }, refreshTokenSecret, {
expiresIn: '12h',
console.log('\nrefresh token JWT\n', refreshToken);
const accessTokenPayload = {
sub: '1',
jti: uuid(),
const accessToken = jwt.sign(accessTokenPayload, secret, {
expiresIn: '1h',
console.log('access token JWT\n', accessToken);
console.log('\n\nDecoding refresh token back\n');
const payload: any = jwt.decode(refreshToken);
console.log('refresh token payload from JWT', payload);
const decipher = crypto.createDecipheriv(algorithm, key, iv);
const decrypted =
decipher.update(, 'hex', 'utf8') +'utf8');
console.log('refresh token decrypted', decrypted);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment