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:)
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' })
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.