Skip to content

Instantly share code, notes, and snippets.

@vitormalencar
Created March 13, 2021 14:05
Show Gist options
  • Save vitormalencar/5657b5231cb298ee8d6149ec6cb57498 to your computer and use it in GitHub Desktop.
Save vitormalencar/5657b5231cb298ee8d6149ec6cb57498 to your computer and use it in GitHub Desktop.
JWT refresh token explain
require('dotenv').config()
const express = require('express')
const app = express()
const jwt = require('jsonwebtoken')
app.use(express.json())
// Aqui salvando os tokens nesse array apenas para fins didaticos
// no mundo real vc deve guardar isso em algum banco
let refreshTokens = []
app.post('/token', (req, res) => {
const refreshToken = req.body.token
// Verifica se existe um refresh Token na requisição
if (refreshToken == null) return res.sendStatus(401)
// Verifica se o token passado na requisição está presente na lista de refreshtokens
if (!refreshTokens.includes(refreshToken)) return res.sendStatus(403)
// Verifica o token e gera o novo token de acesso
jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403)
const accessToken = generateAccessToken({ name: user.name })
res.json({ accessToken: accessToken })
})
})
app.delete('/logout', (req, res) => {
// Deleta o refresh token existente do banco
refreshTokens = refreshTokens.filter(token => token !== req.body.token)
res.sendStatus(204)
})
app.post('/login', (req, res) => {
const username = req.body.username
const user = { name: username }
// Gera o token de acesso
const accessToken = generateAccessToken(user)
// Cria um refresh token para esse usuario
const refreshToken = jwt.sign(user, process.env.REFRESH_TOKEN_SECRET)
refreshTokens.push(refreshToken)
res.json({ accessToken: accessToken, refreshToken: refreshToken })
})
function generateAccessToken(user) {
return jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '5s' })
}
app.listen(4000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment