0

So i was learning about JWT authentication for user login in MERN project using cors npm.I am able to generate the jwt and also able to store it in the DB , but i am not able to see my cookie being stored in the browser.

This is my generateAuthToken() function present in the schema file in express server, here i am generating a jwt & returning it -

userSchema.methods.generateAuthToken = async function(){
try{
        //generate token
        const token = jwt.sign({_id:this._id.toString()} , process.env.SECRET_KEY);
        
        //stored the generated token in our document
        this.tokens = this.tokens.concat({token : token});

        //saved the changes made in the document
        await this.save();

        //returning the token generated when called
        return token;

}catch(err){
    console.log(err);
}

}

and calling the generateAuthtoken() function in the index.js present in express server.The returned token is stored in the 'token' -

const token = await userLogin.generateAuthToken();
        //console.log(token);


    //storing logged in tokens inside cookies
        res.cookie("logintoken" , token , {
            expires : new Date(Date.now() + 60000), //60sec from the time we store the token inside the cookie
            httpOnly : true
        });

And in the frontend react code , i am sending a credentials header inside fetch api , which calls to login route present in my express server at port 4000 -

const response = await fetch('http://localhost:4000/login',{
                method : "POST",
                credentials: 'include',
                headers : {
                    "Content-Type" : "application/json"
                },
                body : JSON.stringify({
                        email : email,
                        password : password
                })
        });

I am using cors npm package for cross-region requests in my express server -

   const cors = require('cors');

   app.use(cors());

And in my browser console ,i am facing this error -

enter image description here

but when i check in my browser , cookie is not getting stored in the storage -

enter image description here

To summarise , i am generating a jwt and returning it inside the function.Then storing that returned token inside a cookie named 'logintoken'.But that cookie is not getting stored in the browser.

I was researching on this and was able to find some threads stating that we also have to define some headers in cors so that the browser is able to store the cookie.But i was not able to figure out how to add as well as which headers are required to achieve this.I have worked before with cookies & jwt , but this is my first time learning with react , express & cors npm.Thank you for your response.

Bhavesh Damor
  • 61
  • 2
  • 14
  • Check out this package [CORS](https://www.npmjs.com/package/cors) – Medi Apr 16 '21 at 09:42
  • @Medi I read the 'configuration options' part where it talked about 'Access-Control-Allow-Origin' but was not able to wrap my head around it.Can you provide me with an example on how to use it ? thank you for responding. i was referencing this link - https://stackoverflow.com/questions/46288437/set-cookies-for-cross-origin-requests – Bhavesh Damor Apr 16 '21 at 10:48

1 Answers1

1

here is a code snippet from my current app

app.use(
    cors({
        credentials: true,
        origin: `http://${process.env.REACT_APP_SERVER_HOST}:${process.env.PORT}`,
    })
);
Medi
  • 1,026
  • 2
  • 9
  • 12
  • so i need to put my frontend reacts http address inside origin , right? – Bhavesh Damor Apr 16 '21 at 10:54
  • I believe it doesn't accept the all-origin `*` value in the case of using cookies. – Medi Apr 16 '21 at 10:55
  • i added `app.use(cors({ credentials : true, origin:'http://localhost:3000' }));` And the cookie got stored in the browser but a warning showed up stating `Cookie “logintoken” will be soon rejected because it has the “SameSite” attribute set to “None” or an invalid value, without the “secure” attribute. ` – Bhavesh Damor Apr 16 '21 at 10:58
  • I added `SameSite : 'none'` , now an error showed up saying `cors request didnot success`. – Bhavesh Damor Apr 16 '21 at 11:03
  • Try to set it to `SameSite=Lax`? – Medi Apr 16 '21 at 11:05
  • i am able to store the cookie and no error is showing in my console too.I added `sameSite : 'none', secure : true` inside res.cookie().but i dont know what these headers mean.I also tried using `SameSite:Lax` and it also worked , i dont know how – Bhavesh Damor Apr 16 '21 at 11:09
  • more explanation [sameSite](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite). – Medi Apr 16 '21 at 11:12
  • i was reading the same article just now.I think my issue is resolved.Thank you for your time , really appreciate it!I think i should be `SameSite : ;none` with `secure` attribute. – Bhavesh Damor Apr 16 '21 at 11:17