Home > Back-end >  JWT web token auth
JWT web token auth

Time:02-05

Can someone explain me why my generated token does not pass middleware?

token creation:
  const createToken = (id) => {
    return jwt.sign({ id }, process.env.JWT_SECRET_KEY);
  }

middleware and rest of code

const getUserFromToken = (req) => {
const token = req.headers.authorization.split(' ')[1];
const user = jwt.verify(token, process.env.JWT_SECRET_KEY);
return user;
> }

const verifyToken = (req, res, next) => {
try {
getUserFromToken(req);
next();
catch(e) {
res.send({ error: 'Invalid Token' });
>   }
> }
app.get('/atendees', verifyToken, (req, res) => {
const user = getUserFromToken(req);

connection.execute('SELECT * FROM event WHERE userId=?', [user.id], (err, events) => {
res.send(events);
>   });
> });

Token is generated and online debuger shows its valid. But my middleware dos not pass.

CodePudding user response:

There are various comments here. First, it seems like there is a problem with the try/catch block not properly written:

try {
  getUserFromToken(req);
} catch(e) {
  res.send('Invalid');
  return;
}
next();

You can use the middleware in order to add the user to the request object

const getUserFromToken = (req) => {
const token = req.headers.authorization.split(' ')[1];
const user = jwt.verify(token, process.env.JWT_SECRET_KEY);
req.user = user;
}

then in the controller itself you won't need to call the getUserFromToken function one more time

CodePudding user response:

Sorry code was working it was my stupid mistake, somehow I managed to put jwt import as a comment...

  • Related