Skip to content

Instantly share code, notes, and snippets.

@zfael
Last active August 13, 2020 18:59
Show Gist options
  • Save zfael/ecb0402e4562deabbd9e6bb5b2bd58bc to your computer and use it in GitHub Desktop.
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',
secret,
};
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') +
cipher.final('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(payload.data, 'hex', 'utf8') + decipher.final('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