Laravel 作为代理和使用 guzzle 处理 cookie

Laravel as a proxy and cookie handling with guzzle

事情是这样的,一个 AngularJS 应用程序向我的 API (Laravel) 发出 post 登录请求。然后 Laravel 使用 Guzzle 向另一个 API 发出请求。这个 API returns 一个 cookie,Laravel 将发送给 AngularJS。

现在,在 AngularJS 发出的后续请求中,将发送此 cookie,Laravel 将其注入后续的 Guzzle 请求。

我的登录方式:

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'));
    }

如何 "sync" Laravel cookie 和 Guzzle cookie?

我正在使用 Laravel 5 和最新的 Guzzle (6.0.1)。

您可以尝试按照 documentation 中指定的方式手动添加 CookieJar。因此您的客户的 cookie 将在请求中使用。

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

我能够使用 Cookie Jar

从 Guzzle 请求中获取创建的 cookie
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;
}