Laravel作为代理和cookie处理与guzzle

时间:2015-06-18 16:17:57

标签: php laravel cookies laravel-5 guzzle

在此处,一个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)。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

我可以使用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;
}