Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

273
Visualizações
Stuck at JWT verify (with Redis)

I am using Node.js plus a package called jwt-redis for creating and verifying authentication tokens in my API, this way I can then destroy them from redis db and logout.

I have already achieved the first part, token creation via jwtr.sign() method. The token is successfully created from a payload and a secret and then included in the response body, as well as a new key in redis.

Now, I am trying to implement a function to authenticate the token, which mainly gets the authorization header from the requests (it is printed correctly at console), connects the redis client (apparently OK too) and finally tries to verify it.

My code is as follows:

async function authenticateToken(req, res, next) {
    // verify if user already exists
    const authHeader = req.header('Authorization')
    // console.log('autheader', authHeader)

    const token = authHeader && authHeader.split(' ')[1] //returns or undenifed or the token
    if (token == null) return res.status(401).json({ Error: 'Usuario no registrado' })
    console.log('token:' + token)

    const redis = require('redis');
    const JWTR =  require('jwt-redis').default;
    //ES6 import JWTR from 'jwt-redis';
    const redisClient = redis.createClient();
    const jwtr = new JWTR(redisClient)

    await redisClient.connect().then(function() {
        console.log("Redis plugged in.")
    })

    jwtr.verify(token, process.env.ACCESS_TOKEN_SECRET, function(err, user) {
        if(err) return res.status(401).json({ Error: 'Usuario no registrado' })
        console.log('user'+user)
        req.USER = user
        next()
    })
}

However, as said, it gets stucked at jwtr.verify(). Console prints both the token and the message "Redis plugged in", but nothing else happens. Application keeps running and postman call's button remains "Sending" until I force node to stop.

As that method returns a promise, so I have tried with both then and await with no success.

Any idea of what's happening here, guys?

I will really appreciate your help :)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

from the documentation

jwtr.verify(token, secretOrPublicKey, [options]): Promise

you are handling that with callback

so I think that you have to modify your code in this way

jwtr.verify(token, process.env.ACCESS_TOKEN_SECRET).then(user => {
   console.log('user'+user)
        req.USER = user
        next()
      }, err => {
       res.status(401).json({ Error: 'Usuario no registrado' })
}) 
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda