Hi all,First thing to say is that I am new to node.js, I am learning but in this case I am running stuck in the following, hope you guys can give me a push in the back ;):In a nutshell:With express I have created routes for register, login and profile. The profile route is behind 'auth' middleware. For the front-end I have the same routes with HTML (handlebars) forms. Register is working, the user is added in the mongodb with an generated json web token. The login route is also working, at least, I think; it runs in my try block and no error is created.At the login route I am doing the following:router.post('/login', async (req, res) => { try { const user = await User.findByCredentials(req.body.email, req.body.password) const token = await user.generateAuthToken() res.cookie('jwt',token, { httpOnly: true, secure: false, maxAge: 3600000 }) res.redirect('/login') } catch (e) { res.send('fail!').redirect('/profile') } }) So I am creating an session httponly cookie where the jwt token is being stored. I see the cookie being created within the session.But when I am trying to use this cookie for going to the "profile" route, which is behind auth middleware, it fails.My auth is looking like this:const jwt = require('jsonwebtoken') const User = require('../models/user') const auth = async (req, res, next) => { try { const token = req.header('Authorization').replace('Bearer ', '') const decoded = jwt.verify(token, process.env.JWT_SECRET) const user = await User.findOne({ _id: decoded._id, 'tokens.token': token }) if (!user) { throw new Error() } req.token = token req.user = user next() } catch (e) { res.status(401).send({ error: "Please authenticate." }) } } module.exports = auth I think it is failing because of the 'Authorization' header. But I am missing some knowledge here.Can you guys help me pushing me into the right direction?Thanks in common!
Submitted September 24, 2020 at 09:29AM by RWMJ19
No comments:
Post a Comment