Vergil333
Vergil333

Reputation: 663

Response header Set-Cookie doesn't store cookies in browser

I'm setting 2 cookies in response from backend to the browser. One that is secure HTTPOnly (it's refreshToken) and the other one without those parameters so it's accessible to JavaScript (carrying information about refreshToken is set and when it expires).

Cookies in response:

enter image description here

Neither of those two is set in browser. I studied all about cookies and I'll be honest, I'm lost here and need your help.

At first it was working very well on my localhost environment (backend on localhost:8080, frontend on localhost:3000). Then I made deploy and there it was NOT working. I tested again on localhost and I checked "Disable cache" to prevent unwanted behaviour and it is not working even there.

I'll mention that I'm using CORS, not sure if that can may interfere:

enter image description here

I tested this both in Chrome and Firefox.

Upvotes: 7

Views: 11556

Answers (2)

Universal War One
Universal War One

Reputation: 11

I FINALY figured it out. Cookies are valid. The answer is to set withCredentials = true both in frontend and backend.

I had the same issue.

On the frontend (127.0.0.1:3000), I am using Axios and I needed this:

 return axios
    .post(
        API_LOGIN,
        {
            email,
            password,
        },
        { withCredentials: true }
    ).then(....).catch(....);

On the backend, I am using NestJS and I needed this:

  app.enableCors({
     credentials: true,
     origin: APP_URL,
     exposedHeaders: ['set-cookie','ajax_redirect'],
     preflightContinue: true,
     methods: "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS",
     optionsSuccessStatus: 200,
  });

Upvotes: 1

Vergil333
Vergil333

Reputation: 663

I FINALY figured it out. Cookies are valid. The answer is to set withCredentials = true both in frontend and backend.

First I thought the parameter withCredentials on frontend is used only when we want to send our credentials hidden in secure HttpOnly cookies to which we don't have access to but browser does. Apparently it is also used when we want to set cookies from response. Link to docs.

responses from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request

Secondly, we also have to add withCredentials on backend to CorsFilter (in Spring boot) otherwise we get CORS error.

CorsConfiguration()
    .apply {
        allowedOrigins = listOf(uiUrl)
        allowedHeaders = listOf("*")
        allowedMethods = listOf("*")
        allowCredentials = true
    }

Upvotes: 13

Related Questions