Fabio Antunes
Fabio Antunes

Reputation: 22862

Laravel as a proxy and cookie handling with guzzle

Here's the deal, one AngularJS app makes a post login request to my API (Laravel). Then Laravel does a request with Guzzle to another API. This API returns a cookie, which Laravel will send over to AngularJS.

Now on subsequent requests made by AngularJS, this cookie is sent, Laravel injects it on subsequent Guzzle requests.

My login method:

public function login(AuthRequest $request)
    {
        $credentials = $request->only('email', 'password');
        $response = $this->httpClient->post('_session', [
            'form_params' => [
                'name'     => $credentials['email'],
                'password' => $credentials['password']
            ]
        ]);

        return $this->respond($response->getHeader('Set-Cookie'));
    }

How do I "sync" the Laravel cookie and the Guzzle cookie?

I'm using Laravel 5 and the latest Guzzle (6.0.1).

Upvotes: 1

Views: 3294

Answers (2)

Fabio Antunes
Fabio Antunes

Reputation: 22862

I was able to get the created cookie from the Guzzle request using the Cookie Jar

public function login($credentials){
    $jar = new \GuzzleHttp\Cookie\CookieJar;
    $response = CouchDB::execute('post','_session', [
        'form_params' => [
            'name'     => 'email_'.$credentials['email'],
            'password' => $credentials['password']
        ],
        'cookies' => $jar
    ]);

    $user = CouchDB::parseStream($response);
    //Here I'm using the $jar to get access to the cookie created by the Guzzle request
    $customClaims = ['name' => $credentials['email'], 'token' => $jar->toArray()[0]['Value']];
    CouchDB::setToken($customClaims['token']);

    $payload = \JWTFactory::make($customClaims);

    $token = \JWTAuth::encode($payload);
    $user->token = $token->get();

    return $user;
}

Upvotes: 0

Sigismund
Sigismund

Reputation: 1082

You can try manually adding CookieJar as specified in documentation. So your client's cookies will be used in request.

$jar = new \GuzzleHttp\Cookie\CookieJar();
$client->request('GET', '/get', ['cookies' => $jar]);

Upvotes: 1

Related Questions