Saturday 25 January 2020

Stuck with passing json web token when logging in

Hi,project filesI have a simple login project that provides a user with a jsonwebtoken once they have logged in. Once logged in the user should be forwarded to a hidden route. The system works in postman but when I render it in the browser I always receive 'Access denied'. I don't know how to pass the webtoken over once i've logged in.I've tried looking into cookies to do so and i downloaded a few packages but I just can't get it to work. The files are above if you want to download and view it in the browser. Alternatively, the code where the issue arises from is:BACKEND THAT PASSES THE WEBTOKEN IN THE HEADER router.post('/login', async (req, res, next) => { //CHECK IF EMAIL EXISTS IN DATABASE const user = await userModel.findOne({ email: req.body.email }) if (user == null) { return res.send('Email doesn\'t exist') } const validPassword = await bcrypt.compare(req.body.password, user.password) if (!validPassword) { return res.send('Invalid email or password') } //CREATE AND ASSIGN JSON WEB TOKEN const token = jwtoken.sign({ id: user._id }, process.env.TOKEN_SECRET) res.header('authToken', token) res.redirect('../posts') }) ​CHECKS IF USER HAS TOKEN const auth = async (req, res, next) => { const token = req.header('authToken') if (!token) { return res.status(401).send('Access denied') } try { const verified = jwToken.verify(token, process.env.TOKEN_SECRET) req.user = verified next() } catch (err) { res.status(400).send('Invalid token') } } ​HIDDEN ROUTE - CHECKS THE BLOCK ABOVE TO SEE IF A WEBTOKEN EXISTS router.get('/', authToken, (req, res, next) => { res.send('User logged in') }) ​I don't get how to make this work outside of postman and in my actual browserI think I need to pass it with cookies somhow...but I cant figure out howThanks.

Submitted January 25, 2020 at 02:40PM by stuckloggingin

No comments:

Post a Comment