How to store jwt in cookie and pass it to authentication function when redirecting a page?
Your jwt token cookie does not work because it declares flag secure: true
in the following code:
res.cookie('jwt',token, { httpOnly: true, secure: true, maxAge: 3600000 })
which lead to Secure
flag in HTTP response, indicating this cookie is only available under HTTPS environment:
Set-Cookie:jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1Y2Y2NjNlMTQwMTQyYjE0MzhmZTJjNDMiLCJpYXQiOjE1NTk5MzI5MDd9.T_P8O-j98cs9gtahTzspJjx1qNMSe3M5OAySyeH25fs; Max-Age=3600; Path=/; Expires=Fri, 07 Jun 2019 19:41:47 GMT; HttpOnly; Secure
As your request URL is using HTTP (http://localhost:3000/users/login
), the cookie would be ignored by browser.
From express-session docs:
Only set the secure tag if you're in production.
if (app.get('env') === 'production') { app.set('trust proxy', 1) // trust first proxy sess.cookie.secure = true // serve secure cookies }
First: you can't view the cookie on client side because you set the following ({ secure:true, httpOnly:true})-secure means it should only use the cookie over an https network while-httpOnly means the cookie should be read by any client side Javascript..
Second: did you really add the "Authorization" header after generating the jwt or you just put it in a cookie 🤔
If so, then try:
jwt.verify(token, <your secret>).then(user=> console.log(user)).catch(err=>console.log(err.toString());
For those who may run into same problem in the future