mattematt
mattematt

Reputation: 545

Cookie not setting in Scala Play

I am trying to set a cookie from a response when using the scala play framework. I am creating a cookie called session with its value being a UUID (I do know play comes with its own session management). I can see the response headers contain the set cookie instruction, but the cookie ins't being set.

Below is the scala code in the action in the controller where the cookie is set

val cookie= Cookie("session",
    sessionToken,
    httpOnly=true,
    sameSite=Some(Cookie.SameSite.Lax))

Ok(Json.toJson(res))
  .withCookies(cookie)
// Also tried with .bakeCookies() after the withCookies() call

I can see the cookie header in the response in both FireFox and Chrome. They both show what appears to be a correctly formed cookie in their respective response cookie viewer in their developer tools.

Set-Cookie: session=c0174ed1-ebd3-4a8d-a5b2-5b09a3fe616b; SameSite=Lax; Path=/; HTTPOnly

However, in both browsers the cookie does not get set. I have tried true and false httpOnly, and messing with the maxAge value. I have tried setting the domain to a url and then setting the url in the hosts file as suggested here.

The URL on the react frontend is

http://localhost:49161/login/hydrate

and the endpoint in play is

http://localhost:49162/user/login/rehydrate

I did also try setting the path to /login/hydrate/ on the cookie

The react code on the front end

     // Inside async function
     // methodStrings[method] = "post" in this request
     axios[methodStrings[method]](url, params)
        .then(result => {
          resolve(result);
        })
        .catch(err => {
          console.error(`Error with request to ${url} - ${err}`);
          reject(err.response.status);
        });

And then I console.log the result from awaiting the request

Upvotes: 0

Views: 897

Answers (1)

Pawel Hawro
Pawel Hawro

Reputation: 1536

Problem is in axios (and/or browser).

Based on this issue Cookies headers are present but Cookies are not stored in browser #1553 you need to set withCredentials Axios config to store cookies in browser after request:

  axios.post('domain.com', {
    name: 'name',
    password: 'password'
  }, {
    //AxiosRequestConfig parameter
    withCredentials: true //correct
  })

Upvotes: 1

Related Questions