【问题标题】:Laravel as a proxy and cookie handling with guzzleLaravel 作为代理和 cookie 处理与 guzzle
【发布时间】:2015-09-04 09:45:32
【问题描述】:

这是交易,一个 AngularJS 应用程序向我的 API (Laravel) 发出登录后请求。然后 Laravel 使用 Guzzle 向另一个 API 发出请求。这个 API 返回一个 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'));
    }

如何“同步” Laravel cookie 和 Guzzle cookie?

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

【问题讨论】:

  • 一个简单的想法(我可能误解了这个问题) - 将 Guzzle cookie 保存在 Laravel 会话中并根据需要检索它。
  • 这就是我尝试过的,但是在 Guzzle 上阅读有关 cookie 的文档时,我没有找到为每个请求设置 cookie 的方法。这是 Guzzle 文档 docs.guzzlephp.org/en/latest/quickstart.html#cookies 上关于 cookie 的唯一信息

标签: php laravel cookies laravel-5 guzzle


【解决方案1】:

我能够使用 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;
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 没错,这就是我最终所做的,完全忘了回答我自己的问题
    猜你喜欢
    • 2017-04-08
    • 2016-05-12
    • 2023-03-10
    • 2012-06-28
    • 1970-01-01
    • 2016-10-04
    • 2017-11-19
    • 1970-01-01
    • 2015-11-26
    相关资源
    最近更新 更多