Token refresh with JWT and Node.JS

Asked

Viewed 119 times

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).

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.