Home > Software design >  MERN App with JWT authentication storing token on cookie always returns 401 on requests
MERN App with JWT authentication storing token on cookie always returns 401 on requests

Time:01-02

I am doing a react app and I had the authentication storing the JWT on localstorage, then I read about xss attacks and changed my mind to use cookies to store the JWT token, I have refactor my code to achieve this but after logging I try to do a request but always get unauthorized, I logged the headers sent by the client and the token is being sent, the server have the headers to allow the credentials i.e

res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Credentials', 'true');

but still get 401 error. the code I have is this:

also the React client is running on: request headers

CodePudding user response:

passport.authenticate('jwt') expects authorization header or other similar fields but not cookie.

http://www.passportjs.org/packages/passport-jwt/

There is a different mechanism to use cookies as authorization with passport

http://www.passportjs.org/packages/passport-jwt-cookiecombo/

Edit: passport-jwt-cookiecombo is depreciated. Token can be manually extracted and used in passport.authenticate

Reference: https://alphonso-javier.medium.com/building-httponly-cookie-jwt-authentication-with-passport-js-27ec519b99c1

  • Related