Kaushal Gajjar
Kaushal Gajjar

Reputation: 81

Set-Cookie not working properly in axios call

Explanation

here, I sent one get req to ABC.com/Users/Login using Axios after this I sent a post request to ABC.com/Users/Login with form data and Cookie.

but it does not work properly. It works properly in postmen

My Code

axios.get('ABC.com/Users/Login')
.then(async response => {

   console.log("call login page");
   let tokenKey = "__RequestVerificationToken";
   let tokenValue = "CfDJ8DF1Ubmz1lpEibYtvvnYRTVXaJ-HWILEtqE_A3bGmDrD-yyKyJPbYK7qrcS9AIzezPo5- 
    tOWmcXs6WgYThZP-5qo1o1XXpalkJDEPnBtnVa7EhaUYbY2XNcANuugyWgkIf3-O2-_f5h7mNu960qGIaM";
   const userName="XYZ";
   const pass="test@123";

   let form=new FormData();
   form.append('UserName', userName);
   form.append('Password', pass);
   form.append([tokenKey], tokenValue);

   headers={
        'Cookie':response.headers['set-cookie'];
   }

   await axios.post('ABC.com/Users/Login', form, 
   { headers: {...form.getHeaders(),...headers}})
   .then(async response => {
        console.log(`Login success in ${userName}`);
        console.log("response",response.data);
   })
   .catch(error => {
       console.log(error);
   });

}
.catch(error => {
console.log(error);
});

In the First Axios call, I got:-

Set-Cookie: .AspNetCore.Antiforgery.b02ILwhXMuw=CfDJ8DF1Ubmz1lpEibYtvvnYRTXz_0rOkGhY6OXEw3d3vsDNG81V4IaMPfVZm5Hk3_icgp_ToLDG9xKu2mcM1VtEOMnSCktfZwG7Dj9_549SUiKht6Yv33pozagGjseFsfXI74wBwu-mMJkzgwfPx3jS4OA; path=/; samesite=strict; httponly
Set-Cookie: ABC.Session=CfDJ8DF1Ubmz1lpEibYtvvnYRTViv4PoRc%2F7jhjXdtCo4m1GZbcMf60xe9sOva27QUGL0BvT2A2SQZaCmrXlj%2FVL9lTvower%2B1lF87MQVTwDQKAFoEODlnPfWEM6SsrqDa0tomlRynXOtyCROBltiwNI27vo3uo4Y8jEn834lZ4OHYG3; path=/; samesite=lax; httponly 

I Want to set cookie like this :-

Cookie: .AspNetCore.Antiforgery.b02ILwhXMuw=CfDJ8DF1Ubmz1lpEibYtvvnYRTXz_0rOkGhY6OXEw3d3vsDNG81V4IaMPfVZm5Hk3_icgp_ToLDG9xKu2mcM1VtEOMnSCktfZwG7Dj9_549SUiKht6Yv33pozagGjseFsfXI74wBwu-mMJkzgwfPx3jS4OA; ABC.Session=CfDJ8DF1Ubmz1lpEibYtvvnYRTViv4PoRc%2F7jhjXdtCo4m1GZbcMf60xe9sOva27QUGL0BvT2A2SQZaCmrXlj%2FVL9lTvower%2B1lF87MQVTwDQKAFoEODlnPfWEM6SsrqDa0tomlRynXOtyCROBltiwNI27vo3uo4Y8jEn834lZ4OHYG3

It works in postmen but not in Axios call. Even I used this also but its not working

let cook1 = response.headers['set-cookie'][0].replace(" path=/; samesite=strict; httponly", "");
let cook2 = response.headers['set-cookie'][1].replace("; path=/; samesite=lax; httponly", "");
let mainCookie=cook1 + " " + cook2
// mainCookie .AspNetCore.Antiforgery.b02ILwhXMuw=CfDJ8DF1Ubmz1lpEibYtvvnYRTUh3vyphSzebPn04M1GqaH8KdFgWLSBpj5a06HBUhoYBhWdiWJw7Yy5525ZcZ_WblCjF7AzWbhQl2dFbQTwOmzP3K7oa0CLirsSJYkhIG-fHGizaNo-3cf8YdSiECkGhMM; ABC.Session=CfDJ8DF1Ubmz1lpEibYtvvnYRTVEF0LnEGw51HveT2mRMrzmgbHiPWjs8UiPcGcqUpJBhTG1uBSE5NLG8tBwkW1XcJH3OxPcPPsaB30aaRREgroCkO1jw%2BJY6tavDFE0P9RTmk9%2Bf2CTVwaTWYRQgPGam1CWJfODoyCzHwiIdfl8ciJS
headers={
        'Cookie':mainCookie;
}

Upvotes: 8

Views: 38505

Answers (3)

Arnab_Ghosh
Arnab_Ghosh

Reputation: 319

To use Cookies with Axios, you always need to set the withCredentials property.

Not only when you want to send cookie, but also while receiving, this credentials needs to be set to true so that browser can store it.

axios.post(ENDPOINT, JSON.stringify(jsonObject), 
{headers: {'Content-Type': 'application/json'}, withCredentials : true})

On the server side, if your frontend and backend origins are not same, make sure you include the sameSite:'none' and secure:true while sending the cookie:

res.cookie('jwt',token, {httpOnly: true, sameSite: 'none', secure: true , maxAge: 24 * 60 * 60 * 1000})
res.json(jsonObject)

Upvotes: 10

Theophilus Boakye
Theophilus Boakye

Reputation: 101

If you are using axios, set withCredentials to true.

Example:

const api = axios.create({
    baseURL: "http://localhost:5000/api/v1",
    withCredentials: true,
    headers: {
        "Content-type": "application/json",
    },
});

then in your Node, in cors middleware, set

app.use(
    cors({
        credentials: true,
        origin: "http://localhost:3000",
    })
);

Upvotes: 10

Richard Hpa
Richard Hpa

Reputation: 2857

If you want to use Cookies with Axios you need to include the withCredentials property.

axios.post('ABC.com/Users/Login', form, { withCredentials: true });

If it were me I would create a new axios instance and use that one for your calls so that its the same instance of axios for all your api calls.

const axiosInstance = axios.create({
   withCredentials: true
})
axiosInstance.post('ABC.com/Users/Login', form)

Upvotes: 5

Related Questions