1
I am making an API to understand how the Json Web Token, But he’s very simple, you know? So I can’t find content on how to do a token refresh that only lasts 5 minutes in a way that would be simple for me to understand.
Follows the code:
const express = require('express')
const bodyParser = require('body-parser')
const jwt = require('jsonwebtoken')
const app = express()
const SECRET= 'julioceno'
function verifyJwt(req, res, next) {
const token = req.headers['x-access-token']
const index = blackList.findIndex(item => { item === token})
if (index !== -1) return res.status(401).end()
jwt.verify(token, SECRET, (err, decoded) => {
if (err) return res.status(401).end()
next()
})
}
const blackList = []
app
.use(bodyParser.json())
.get('/', (req, res) => {
res.json({ message: "Tudo ok por aqui"})
})
.get('/clientes', verifyJwt,(req, res) => {
res.json([{ id: 1, name: 'Júlião' }])
})
.post('/login', (req, res) => {
if (req.body.user === 'julio' && req.body.password === 123) {
const token = jwt.sign({userId: 1}, SECRET, {expiresIn: 300})
return res.json({auth: true, token})
}
res.status(401).end()
})
.post('/logout', (req, res) => {
blackList.push(req.headers['x-access-token'])
res.end()
})
.listen(3000)
The function verifyJwt
is a middleare that checks whether the token is valid or not or if it is present in the Blacklist, route access will be denied.
The login path is where I authenticate and Gero the token.
The route /clientes
is where I need the token, why if you pay attention to the verifyJwt
is there between the middleware of the route, if the token is invalid I can not use.
In the example ai I just wanted a way to go doing the token refresh if the user is still using the site (in case the API).
Maybe this will answer your question? What is the advantage of using a Refresh Token instead of just the Access Token?
– Luiz Felipe
It is noteworthy that some people are against using Jwts for authentication. And the arguments are decent.
– Luiz Felipe
No bro, that’s not it, I wonder how to implement a refresh ai in the code understand? The question of importance I already understood
– Júlio Nepomuceno