Http-only cookies are not sending in request headers in Axios

123 Views Asked by At

We are going to a new authentication with tokens in http-only cookies.

After login i receive access token and CSRF_COOKIE in Set-Cookies response header. As I know these cookies has to automatically be include in all my next request with the same base-url. enter image description here

And after successful login I am trying to send ping request to check if cookies are sending in headers. But this is not working. As it's shown in request headers there is no cookies provided and I receive 401 error.

enter image description here

I googled a lot and everyone says to add withCredentials: true, and I added it:

checkPing = async () => {
    try{
        const {data} = await axiosApi('/v2/accounts/ping/', {method: 'post', withCredentials: true});
        console.log('response', data)

    }catch (error) {
        console.log('here is error', error)
    }
}

But my tokens from cookies still do not automatically goes to request headers. Please help to understand the problem and how to solve it. Thanks in advice!

UPDATE: The issue was in cookies setting. We changed from SameSite=Lax to SameSite=none, Secure=true. This changes fixed the problem and now cookies sends automatically in request headers. Thanks for everyone! Hope this info gonna be helpful!

1

There are 1 best solutions below

0
Gary Archer On

Your API issued cookies are likely being dropped because they are cross site:

In recent years, cookie changes to protect user privacy were introduced in RFC6265bis. Section 5.2 explains how you are making cross site requests. Browsers now drop cross site cookies aggressively.

To fix your problem, start by running the API locally, along with the browser client. Eg add this entry to your /etc/hosts file and use the web domain in the browser rather than localhost. Also use the same scheme, such as HTTP, for both components. The port can differ.

127.0.0.1 www.example.com api.example.com

If cookies then stick, update your deployment to also use a sibling domain relationship as above. People often use a reverse proxy to route to real APIs, eg: