DocTolly's avatar

Can't access httponly cookie in Cookie::get()

Laravel backend as API (rota.test), React Frontend (localhost:3000) (seperate from each other)

I create and queue a http only cookie successfully on hitting an authentication route. Access token / expiration time is returned to the user, and the refresh token is stored in a httponly cookie

    protected function setRefreshTokenCookie(string $refreshToken)
    {
       Cookie::queue(
           Cookie::make(
            self::$refresh_token_cookie_name,
            $refreshToken,
            14400, // 10 days
            null,
            null,
            false,
            true
            )
        );
    }

I can see see the cookie in the XHR request response http://prntscr.com/smwbez

When I send my user to a refresh-token route, the cookie cannot be retrieved (returns null)

    protected function getRefreshTokenCookie()
    {
        return Cookie::get(self::$refresh_token_cookie_name);
    }

I have AddQueuedCookiedToResponse in my API middleware. EncryptCookies is not in the APi middleware, but have tried adding the cookie name to encryption exceptions anyway (no luck)

Any explanation of why I can't retrieve the cookie?

0 likes
3 replies
DocTolly's avatar

To add, I am using laravel-cors, this is my cors.php config


    'paths' => ['api/*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['http://localhost:3000'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

My axios calls to the refresh-token route are using withCredentials:true

DocTolly's avatar

Instead of adding Cookie to queue, I have also tried manually sending it back in the response

return response()->json($response, 200)->withCookie($cookie);

Again, the cookie is sent in the headers and I can see it in the console, but it is not saved into storage and I can't recall it with Cookie::get on the refresh-token route

DocTolly's avatar
DocTolly
OP
Best Answer
Level 2

For anyone else who may come across this problem, add same-site: none when setting the cookie. https://web.dev/samesite-cookies-explained/

           Cookie::make(
            'cookie name',
            'cookie value',
            14400, // time to expire 
            null,
            null,
            false,
            true, 
            false,
            'none'//same-site   <-----
          )

Please or to participate in this conversation.