Hello every One i have been trying this for a day but can't able to find out what i am doing wrong?

Here Class proxy function which gives me access token and refresh token after user enter it's username and password by ajax request i send request to controller where proxy controller function is called

      private function proxy($grantType, array $data = [])
     {

    try {
        $config = app()->make('config');

        $data = array_merge([
            'client_id'     => 'm492pkQPkw5YGa2sBRFvLKPSfkhy9yLbU52DiyDL',
            'client_secret' => 'X96evDo1jq067VMzQoq8UC4iMlfFmm2DTjPQCHba',
            'grant_type'    => $grantType
            ], $data);
        $client = new Client();
        $guzzleResponse = $client->post(sprintf('%s/api/auth/authorize', $config->get('app.url')), [
            'form_params' => $data
            ]);

    } catch(\GuzzleHttp\Exception\BadResponseException $e) {
        $guzzleResponse = $e->getResponse();

    }

    $response = json_decode($guzzleResponse->getBody());

    if (property_exists($response, "access_token")) {
        $cookie = new \Illuminate\Cookie\CookieJar();
        $crypt  = app()->make('encrypter');
        $encryptedToken = $crypt->encrypt($response->refresh_token);

        $cookie->queue('refreshToken',
            $crypt->encrypt($encryptedToken),
            604800, 
            null,
            null,
            true,
            true 
            );

        $response = [
        'accessToken'            => $response->access_token,
        'accessTokenExpiration'  => $response->expires_in
        ];
    }

    $response = response()->json($response);
    $response->setStatusCode($guzzleResponse->getStatusCode());

    $headers = $guzzleResponse->getHeaders();
    // attach headers 

    return $response;
}

now as you can all see that is i am trying to add cookie to header named as refresh token but it;s not added only laravel seesion cookie is added

These are request headers

Access-Control-Allow-Headers:origin, x-requested-with, content-type, Authorization
Access-Control-Allow-Headers:origin, x-requested-with, content-type, Authorization
Access-Control-Allow-Methods:PUT, GET, POST, DELETE, OPTIONS
Access-Control-Allow-Methods:PUT, GET, POST, DELETE, OPTIONS
Access-Control-Allow-Origin:
Access-Control-Allow-Origin:

Cache-Control:must-revalidate, private
Connection:close
Content-Length:91
Content-Type:application/json
Date:.............
ETag:"53cd7d5588e00fc19f119e9fbcb40bd862d32e00"
Server:Apache.................
Strict-Transport-Security:max-age=63072000; includeSubdomains
Strict-Transport-Security:max-age=63072000; includeSubdomains
Vary:Authorization
X-Content-Type-Options:nosniff
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-Frame-Options:DENY

And This is Response Headers

Content-Type:application/x-www-form-urlencoded; charset=UTF-8

Cookie:laravel_session=eyJpdiI6IlhPNWpMdTI5a2xo..........................

X-CSRF-Token:null
X-Requested-With:XMLHttpRequest

According to Docs Cookie::queue will automatically add cookies to resposne but i don't get it why it's not added.I am trying this on both postman and web.What i am trying to do is set httpOnly Cookie
Any Help will be appreciated

Dani AI

Generated

the issue is that you are creating a brand-new CookieJar and queueing the cookie on that instance. Since it is not the app’s jar, the queued cookie never gets attached to the response Laravel actually returns. Either attach the cookie directly to the response, or use the framework-managed jar/facade.

Example attaching to the same response instance:

return response()->json([
    'accessToken'           => $accessToken,
    'accessTokenExpiration' => $expiresIn,
])->cookie(
    'refreshToken',
    $refreshToken,          // no manual encryption needed
    10080,                  // 7 days in minutes
    '/',                    // path
    null,                   // domain (set explicitly if using subdomains)
    true,                   // secure (HTTPS only)
    true                    // httpOnly
);

Laravel’s docs show attaching cookies via response()->cookie(...) and also support using the Cookie facade to queue on the framework jar. Both approaches bind the cookie to the outgoing response. See “Attaching Cookies To Responses” in the Laravel 5.4 docs. Laravel 5.4 HTTP Requests: Cookies. (laravel.com)

A couple more gotchas from your snippet:

  • The cookie lifetime parameter is minutes, not seconds. For 7 days use 10080, not 604800.
  • You are double-encrypting the token, and Laravel’s EncryptCookies middleware will encrypt again anyway. Pass the plain value unless you have a specific reason to pre-encrypt.

Lastly, your headers show Access-Control-Allow-Origin: *. If this request is cross-origin, browsers will ignore Set-Cookie unless you:

If it is truly cross-site, also set SameSite=None; Secure for the cookie.

Note:request and resposne headers are exchanged

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.