1 回答
TA贡献1796条经验 获得超7个赞
事实证明,通过为 Symfony 尝试其他 HTTP 客户端组件而不是本机组件,这个任务更容易完成。所以我暂时把 Symfony HttpClient 和 HttpBrowser 放在一边。我设法用 guzzlehttp/guzzle 6.3.3 版解决了这个问题。这是我的控制器功能中的样子:
use GuzzleHttp\Client;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
public function init(Request $request): JsonResponse {
$client = new Client([
'base_uri' => 'an external domain',
'cookies' => true
]);
// get the 302 response, without following
$response = $client->get('path',[
'allow_redirects' => false
]);
// get the cookie from the 302 response
$jar = new \GuzzleHttp\Cookie\CookieJar(true,[$response->getHeader('Set-Cookie')]);
// follow the redirect manually, with the cookie from the 302 response
$redirectResponse = $client->request('GET', $response->getHeader('Location')[0], [
'cookies' => $jar
]);
$jsonResponse = new JsonResponse(['message' => 'my message'],200);
$originalCookie = Cookie::fromString($response->getHeader('Set-Cookie')[0]);
$newCookie = Cookie::create(
$originalCookie->getName(),
$originalCookie->getValue(),
$originalCookie->getExpiresTime(),
'/',
'my domain',
false,
true,
$originalCookie->isRaw(),
$originalCookie->getSameSite()
);
$jsonResponse->headers->setCookie($newCookie);
return $jsonResponse;
}
cookie 不能从响应中获取,否则它永远不会被发回,因为域或路径不匹配。因此,我创建了一个与原始 cookie 非常相似的新 cookie,然后将其发送回浏览器。这样 cookie 会在后续请求中返回,并且数据内容可以被转发。
这里出现的其他问题是必须在外部服务器上处理的同源要求。
我仍然对如何使用本地 Symfony 4.3 组件完成所有这些操作感兴趣,或者,如果有人可以确认这是不可能的。
- 1 回答
- 0 关注
- 359 浏览
添加回答
举报
