I am making an auth system using JWT. I have a /login POST route, /user/:username GET route and an auth middleware. When I successfully /login as a user I will get redirected to /user/:username which has a auth middleware.This is how my login route looks like:router.post('/login', async (req, res) => { const user = await User.findOne({ email: req.body.email }).select('-authToken'); const passwordsMatch = await bcrypt.compare(req.body.password, user.password); if (passwordsMatch) { const token = user.generateAuthToken(); res.header('x-auth-token', token).send(user); } else { res.send(false); } }); Here I am comparing the hashed password and if it matches I generate auth token and set it as a 'x-auth-token' header using res.header('x-auth-token', token) , it the passwords don't match just send false.My middleware looks like this:module.exports = function (req, res, next) { const token = req.headers['x-access-token'] || req.headers['authorization']; if (!token) return res.status(401).send('Access denied. No token provided.'); try { const decoded = jwt.verify(token, config.get('privatekey')); req.user = decoded; console.log(req.user); next(); } catch (ex) { res.status(400).send('Invalid token.'); } }; The problem that I am getting is that req.headers['x-access-token'] or req.headers['authorization'] are not set, so I always get 401 response status. This is strange, because I can see the token created inside the response headers of my login post request, but I think that they are only created there. If I go to a route that has the auth middleware it doesn't find the headers.My "protected" route looks like this:router.get('/:username', auth, async (req, res) => { let user = await User.findOne({ username: req.params.username }).select('-password -authToken'); res.json(user); }); If you need more information, just ask. :)Thank you for reading.
Submitted August 05, 2019 at 09:59PM by AmirSaran
No comments:
Post a Comment