public function download($url) { $cookies = $this->getSession()->getCookie($this->sessionName); $cookie = SetCookie::fromString($cookies); $jar = new CookieJar(); $jar->setCookie($cookie); $client = new Client(['base_url' => $this->getSession()->getCurrentUrl()]); $this->response = $client->get($url, ['cookies' => $jar]); }
public function __construct(\GuzzleHttp\Client $guzzle, SerializerInterface $serializer, CookieJar $cookieJar) { $this->guzzle = $guzzle; // @TODO temporary solution, as authentication does not work ATM. $cookieJar->setCookie(SetCookie::fromString('SID="AuthKey 23ec5d03-86db-4d80-a378-6059139a7ead"; expires=Thu, 24 Nov 2016 13:52:20 GMT; path=/; domain=.sketchup.com')); $this->serializer = $serializer; }
protected function preConstructHealthChecker() { $cookieJar = new CookieJar(); foreach ($this->getCookies() as $cookieData) { $cookieJar->setCookie(new SetCookie($cookieData)); } $this->getHttpClient()->getEmitter()->attach(new HttpCookieSubscriber($cookieJar)); }
public function testAuthenticate() { $cookieJar = new CookieJar(); $client = new Client(['cookies' => $cookieJar]); $authenticator = new CookieBasedAuthenticator(FSHARE_TEST_EMAIL, FSHARE_TEST_PASSWORD, new ReferralRequestDecorator()); $authenticator->authenticate($client); static::assertTrue(is_string($cookieJar->getCookieValue('session_id'))); static::assertTrue($cookieJar->getCookieValue('session_id') !== ''); }
/** * Returns only the final results. To enable interim results, * use session-based requests or Websockets API. Endianness * of the incoming audio is autodetected. Audio files larger * than 4 MB are required to be sent in streaming mode * (chunked transfer-encoding). * * Streaming audio size limit is 100 MB. In streaming mode, * the connection is closed by the server if no data chunk * is received for more than 30 seconds and the last chunk * has not been sent yet (if all data has been sent, it can * take more than 30 seconds to generate the response and the * request will not time out). * * Use getUrlWithSession() to prevent the session from expiring. * The connection is also closed by the server if no speech is * detected for "inactivity_timeout" seconds of audio (not * processing time). This time can be set by "inactivity_timeout" * parameter; the default is 30 seconds. * * @param string $pathToFile * @param string $contentType * @param bool $uri * * @return $this */ public function recognize($pathToFile, $contentType = self::CONTENT_TYPE, $uri = false) { $uri = $uri ?: $this->getUrlWithSession('/recognize'); foreach ($this->getSetCookieHeader() as $cookie) { $cookie = SetCookie::fromString($cookie); $cookie->setDomain('stream.watsonplatform.net'); $this->cookieJar->setCookie($cookie); } $data[] = ['name' => 'audio_file', 'contents' => fopen($pathToFile, 'r')]; $this->recognize = $this->request($uri, 'POST', ['multipart' => $data, 'query' => ['continuous' => 'true', 'inactivity_timeout' => -1], 'cookies' => $this->cookieJar, 'headers' => ['content-type' => $contentType]]); return $this; }
/** * Sets up and fills a cookie jar * * @param [array] $params Request data to fill jar with * @return [GuzzleHttp\Cookie\CookieJar] $jar */ static function fillCookieJar($params) { $jar = new CookieJar(); $cookies = array(); if ($session = Session::instance()->get('session', false)) { $cookies['X-Pantheon-Session'] = $session; } if (isset($params['cookies'])) { $cookies = array_merge($cookies, $params['cookies']); } $jar->fromArray($cookies, ''); return $jar; }
public function setUp() { $this->loadHttpClientFixtures(array('HTTP/1.1 200 Ok', 'HTTP/1.1 200 Ok', 'HTTP/1.1 200 Ok', 'HTTP/1.1 200 Ok')); $webPage = new WebPage(); $webPage->setHttpResponse($this->getHttpFixtureFromHtmlDocument('example16', 'http://example.com')); $cookieJar = new CookieJar(); foreach ($this->getCookies() as $cookieData) { $cookieJar->setCookie(new SetCookie($cookieData)); } $this->getHttpClient()->getEmitter()->attach(new HttpCookieSubscriber($cookieJar)); $checker = $this->getDefaultChecker(); $checker->setWebPage($webPage); $checker->getAll(); }
private function getCrumbVaue() { foreach ($this->jar->toArray() as $cookie) { if (strtolower($cookie['Name']) === 'crumb') { return $cookie['Value']; } } }
public function testGetWithCookies() { $request = new Request('GET', 'http://local.example'); $jar = CookieJar::fromArray(['Foo' => 'Bar', 'identity' => 'xyz'], 'local.example'); $curl = $this->curlFormatter->format($request, ['cookies' => $jar]); $this->assertNotContains("-H 'Host: local.example'", $curl); $this->assertContains("-b 'Foo=Bar; identity=xyz'", $curl); }
/** * Save cookies to the client's session. * * @param \GuzzleHttp\Cookie\SetCookie $cookie * * @return bool */ public function setCookie(SetCookie $cookie) { $successful = parent::setCookie($cookie); if ($successful) { $this->cookie->make($cookie->getName(), $cookie); return true; } return false; }
public function setUp() { $this->setTestFixturePath(get_class($this)); $this->setHttpFixtures($this->getHttpFixtures($this->getFixturesDataPath() . '/HttpResponses')); $cookieJar = new CookieJar(); foreach ($this->getCookies() as $cookieData) { $cookieJar->setCookie(new SetCookie($cookieData)); } $this->getHttpClient()->getEmitter()->attach(new HttpCookieSubscriber($cookieJar)); $configuration = new Configuration(); $configuration->setUrlToValidate('http://example.com/'); $configuration->setHttpClient($this->getHttpClient()); $this->wrapper = $this->getNewCssValidatorWrapper(); $this->wrapper->setConfiguration($configuration); $this->wrapper->enableDeferToParentIfNoRawOutput(); $this->wrapper->setCssValidatorRawOutput($this->getFixture('no-messages.txt')); $this->wrapper->validate(); }
/** * Get cookie jar, hidratates one if it is empty * * @param string|UriInterface $base_uri Optional base uri * @return CookieJar The cookie jar */ public function getCookieJar(array &$options, $base_uri = null) { if ($this->coockieJar->count() <= 0 || !$this->loginMade) { $this->obtainCookies($options, $base_uri); } if (isset($options['auth-cookie'])) { unset($options['auth-cookie']); } return $this->coockieJar; }
/** * 将自定义的cookie追加进请求 * @param Api $api * @return CookieJar */ protected function getCookies(Api $api) { if ($cookies = $api->getCookies()) { $this->cookieContainer->setCookies($cookies); } //将cookie自身的容器交还给guzzle foreach ($this->cookieContainer->getCookies() as $cookie) { $this->cookies->setCookie(new SetCookie(['Name' => $cookie->getName(), 'Value' => $cookie->getValue(), 'Domain' => $cookie->getDomain() ?: $api->getUrl()->getHost(), 'Path' => $cookie->getPath(), 'Expires' => $cookie->getExpires()])); } return $this->cookies; }
public function authenticate() { // go to google.com to get some cookies $request = $this->guzzleClient->createRequest('GET', 'http://www.google.com/ncr', ['cookies' => $this->cookieJar]); $response = $this->guzzleClient->send($request); // get google auth page html and fetch GALX $request = $this->guzzleClient->createRequest('GET', self::AUTH_URL, ['cookies' => $this->cookieJar]); $response = $this->guzzleClient->send($request); $content = $response->getBody()->getContents(); $document = new \DOMDocument(); @$document->loadHTML($content); $inputElements = $document->getElementsByTagName("input"); $params = []; foreach ($inputElements as $input) { $params[$input->getAttribute("name")] = $input->getAttribute("value"); } $params['Email'] = $this->email; $params['Passwd'] = $this->password; $params['pstMsg'] = '1'; $params['continue'] = 'http://www.google.com/trends'; // authenticate $request = $this->guzzleClient->createRequest('POST', self::AUTH_URL, ['cookies' => $this->cookieJar]); $query = $request->getQuery(); foreach ($params as $key => $param) { $query->set($key, $param); } $response = $this->guzzleClient->send($request); // verify sign in if needed if (strpos($response->getEffectiveUrl(), 'LoginVerification') !== false) { $content = $response->getBody()->getContents(); $document = new \DOMDocument(); @$document->loadHTML($content); $inputElements = $document->getElementsByTagName("input"); $params = []; foreach ($inputElements as $input) { $params[$input->getAttribute("name")] = $input->getAttribute("value"); } $params['challengetype'] = 'RecoveryEmailChallenge'; $params['emailAnswer'] = $this->recoveryEmail; $url = substr($response->getEffectiveUrl(), 0, strpos($response->getEffectiveUrl(), '?')); $request = $this->guzzleClient->createRequest('POST', $url, ['cookies' => $this->cookieJar]); $query = $request->getQuery(); foreach ($params as $key => $param) { $query->set($key, $param); } $response = $this->guzzleClient->send($request); } // update cookies $response = $this->guzzleClient->get('https://www.google.com/accounts/CheckCookie?chtml=LoginDoneHtml', ['cookies' => $this->cookieJar], ['headers' => ['Referrer' => 'https://www.google.com/accounts/ServiceLoginBoxAuth']]); // set language for trends $I4SUserLocale = new setCookie(['Name' => 'I4SUserLocale', 'Value' => $this->language, 'Domain' => 'www.google.com', 'Path' => '/trends', 'Secure' => true, 'HttpOnly' => true]); $this->cookieJar->setCookie($I4SUserLocale); return $this; }
protected function doRequest($request) { $headers = array(); foreach ($request->getServer() as $key => $val) { $key = strtolower(str_replace('_', '-', $key)); $contentHeaders = array('content-length' => true, 'content-md5' => true, 'content-type' => true); if (0 === strpos($key, 'http-')) { $headers[substr($key, 5)] = $val; } elseif (isset($contentHeaders[$key])) { $headers[$key] = $val; } } $cookies = CookieJar::fromArray($this->getCookieJar()->allRawValues($request->getUri()), $request->getServer()['HTTP_HOST']); $requestOptions = array('cookies' => $cookies, 'allow_redirects' => false, 'auth' => $this->auth); if (!in_array($request->getMethod(), array('GET', 'HEAD'))) { if (null !== ($content = $request->getContent())) { $requestOptions['body'] = $content; } else { if ($files = $request->getFiles()) { $requestOptions['multipart'] = []; $this->addPostFields($request->getParameters(), $requestOptions['multipart']); $this->addPostFiles($files, $requestOptions['multipart']); } elseif (!empty($headers['content-type']) && 'multipart/form-data' == $headers['content-type'] && !$files) { $requestOptions['multipart'] = []; $this->addPostFields($request->getParameters(), $requestOptions['multipart']); } else { $requestOptions['form_params'] = $request->getParameters(); } } } if (!empty($headers)) { $requestOptions['headers'] = $headers; } $method = $request->getMethod(); $uri = $request->getUri(); foreach ($this->headers as $name => $value) { $requestOptions['headers'][$name] = $value; } // Let BrowserKit handle redirects try { $response = $this->getClient()->request($method, $uri, $requestOptions); } catch (RequestException $e) { $response = $e->getResponse(); if (null === $response) { throw $e; } } return $this->createResponse($response); }
/** * Tests access to routes protected by CSRF request header requirements. * * This checks one route that uses _csrf_request_header_token and one that * uses the deprecated _access_rest_csrf. */ public function testRouteAccess() { $client = \Drupal::httpClient(); $csrf_token_paths = ['deprecated/session/token', 'session/token']; // Test using the both the current path and a test path that returns // a token using the deprecated 'rest' value. // Checking /deprecated/session/token can be removed in 8.3. // @see \Drupal\Core\Access\CsrfRequestHeaderAccessCheck::access() foreach ($csrf_token_paths as $csrf_token_path) { // Check both test routes. $route_names = ['csrf_test.protected', 'csrf_test.deprecated.protected']; foreach ($route_names as $route_name) { $user = $this->drupalCreateUser(); $this->drupalLogin($user); $csrf_token = $this->drupalGet($csrf_token_path); $url = Url::fromRoute($route_name)->setAbsolute(TRUE)->toString(); $domain = parse_url($url, PHP_URL_HOST); $session_id = $this->getSession()->getCookie($this->getSessionName()); /** @var \GuzzleHttp\Cookie\CookieJar $cookies */ $cookies = CookieJar::fromArray([$this->getSessionName() => $session_id], $domain); $post_options = ['headers' => ['Accept' => 'text/plain'], 'http_errors' => FALSE]; // Test that access is allowed for anonymous user with no token in header. $result = $client->post($url, $post_options); $this->assertEquals(200, $result->getStatusCode()); // Add cookies to POST options so that all other requests are for the // authenticated user. $post_options['cookies'] = $cookies; // Test that access is denied with no token in header. $result = $client->post($url, $post_options); $this->assertEquals(403, $result->getStatusCode()); // Test that access is allowed with correct token in header. $post_options['headers']['X-CSRF-Token'] = $csrf_token; $result = $client->post($url, $post_options); $this->assertEquals(200, $result->getStatusCode()); // Test that access is denied with incorrect token in header. $post_options['headers']['X-CSRF-Token'] = 'this-is-not-the-token-you-are-looking-for'; $result = $client->post($url, $post_options); $this->assertEquals(403, $result->getStatusCode()); } } }
/** * @brief 设置请求Cookie * * @param array $cookies 请求Cookie数组 * @param string $domain Cookie域 * * @return Client */ public function setCookies(array $cookies = [], $domain = null) { if (!$cookies) { $this->cookies = []; } else { //没传默认当前base_uri的域 if (!$domain) { $domain = parse_url($this->conf->baseUri, PHP_URL_HOST); } $this->cookies = \GuzzleHttp\Cookie\CookieJar::fromArray($cookies, $domain); } return $this; }
/** * Proxy authenticates to a target service. * * Returns cookies from the proxied service in a * CookieJar object for use when later accessing resources. * * @param string $target_service * The service to be proxied. * * @return \GuzzleHttp\Cookie\CookieJar * A CookieJar object (array storage) containing cookies from the * proxied service. * * @throws CasProxyException */ public function proxyAuthenticate($target_service) { // Check to see if we have proxied this application already. if (isset($_SESSION['cas_proxy_helper'][$target_service])) { $cookies = array(); foreach ($_SESSION['cas_proxy_helper'][$target_service] as $cookie) { $cookies[$cookie['Name']] = $cookie['Value']; } $domain = $cookie['Domain']; $jar = CookieJar::fromArray($cookies, $domain); $this->casHelper->log("{$target_service} already proxied. Returning information from session."); return $jar; } if (!($this->casHelper->isProxy() && isset($_SESSION['cas_pgt']))) { // We can't perform proxy authentication in this state. throw new CasProxyException("Session state not sufficient for proxying."); } // Make request to CAS server to retrieve a proxy ticket for this service. $cas_url = $this->getServerProxyURL($target_service); try { $this->casHelper->log("Retrieving proxy ticket from: {$cas_url}"); $response = $this->httpClient->get($cas_url); $this->casHelper->log("Received: " . htmlspecialchars($response->getBody()->__toString())); } catch (ClientException $e) { throw new CasProxyException($e->getMessage()); } $proxy_ticket = $this->parseProxyTicket($response->getBody()); $this->casHelper->log("Extracted proxy ticket: {$proxy_ticket}"); // Make request to target service with our new proxy ticket. // The target service will validate this ticket against the CAS server // and set a cookie that grants authentication for further resource calls. $params['ticket'] = $proxy_ticket; $service_url = $target_service . "?" . UrlHelper::buildQuery($params); $cookie_jar = new CookieJar(); try { $this->casHelper->log("Contacting service: {$service_url}"); $this->httpClient->get($service_url, ['cookies' => $cookie_jar]); } catch (ClientException $e) { throw new CasProxyException($e->getMessage()); } // Store in session storage for later reuse. $_SESSION['cas_proxy_helper'][$target_service] = $cookie_jar->toArray(); $this->casHelper->log("Stored cookies from {$target_service} in session."); return $cookie_jar; }
private function add_cookies(RequestInterface $request, $value) { if ($value === true) { static $cookie = null; if (!$cookie) { $cookie = new Cookie(); } $request->getEmitter()->attach($cookie); } elseif (is_array($value)) { $request->getEmitter()->attach(new Cookie(CookieJar::fromArray($value, $request->getHost()))); } elseif ($value instanceof CookieJarInterface) { $request->getEmitter()->attach(new Cookie($value)); } elseif ($value !== false) { throw new \InvalidArgumentException('cookies must be an array, ' . 'true, or a CookieJarInterface object'); } }
protected function applyOptions(RequestInterface $request, array $options = []) { $config = $request->getConfig(); $emitter = $request->getEmitter(); foreach ($options as $key => $value) { if (isset(self::$configMap[$key])) { $config[$key] = $value; continue; } switch ($key) { case 'allow_redirects': if ($value === false) { continue; } if ($value === true) { $value = self::$defaultRedirect; } elseif (!isset($value['max'])) { throw new Iae('allow_redirects must be true, false, or an ' . 'array that contains the \'max\' key'); } else { // Merge the default settings with the provided settings $value += self::$defaultRedirect; } $config['redirect'] = $value; $emitter->attach($this->redirectPlugin); break; case 'decode_content': if ($value === false) { continue; } $config['decode_content'] = true; if ($value !== true) { $request->setHeader('Accept-Encoding', $value); } break; case 'headers': if (!is_array($value)) { throw new Iae('header value must be an array'); } // Do not overwrite existing headers foreach ($value as $k => $v) { if (!$request->hasHeader($k)) { $request->setHeader($k, $v); } } break; case 'exceptions': if ($value === true) { $emitter->attach($this->errorPlugin); } break; case 'body': if (is_array($value)) { $this->addPostData($request, $value); } elseif ($value !== null) { $request->setBody(Stream::factory($value)); } break; case 'auth': if (!$value) { continue; } if (is_array($value)) { $type = isset($value[2]) ? strtolower($value[2]) : 'basic'; } else { $type = strtolower($value); } $config['auth'] = $value; if ($type == 'basic') { $request->setHeader('Authorization', 'Basic ' . base64_encode("{$value['0']}:{$value['1']}")); } elseif ($type == 'digest') { // @todo: Do not rely on curl $config->setPath('curl/' . CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); $config->setPath('curl/' . CURLOPT_USERPWD, "{$value['0']}:{$value['1']}"); } break; case 'query': if ($value instanceof Query) { $original = $request->getQuery(); // Do not overwrite existing query string variables by // overwriting the object with the query string data passed // in the URL $value->overwriteWith($original->toArray()); $request->setQuery($value); } elseif (is_array($value)) { // Do not overwrite existing query string variables $query = $request->getQuery(); foreach ($value as $k => $v) { if (!isset($query[$k])) { $query[$k] = $v; } } } else { throw new Iae('query must be an array or Query object'); } break; case 'cookies': if ($value === true) { static $cookie = null; if (!$cookie) { $cookie = new Cookie(); } $emitter->attach($cookie); } elseif (is_array($value)) { $emitter->attach(new Cookie(CookieJar::fromArray($value, $request->getHost()))); } elseif ($value instanceof CookieJarInterface) { $emitter->attach(new Cookie($value)); } elseif ($value !== false) { throw new Iae('cookies must be an array, true, or CookieJarInterface'); } break; case 'events': if (!is_array($value)) { throw new Iae('events must be an array'); } $this->attachListeners($request, $this->prepareListeners($value, ['before', 'complete', 'error', 'progress', 'end'])); break; case 'subscribers': if (!is_array($value)) { throw new Iae('subscribers must be an array'); } foreach ($value as $subscribers) { $emitter->attach($subscribers); } break; case 'json': $request->setBody(Stream::factory(json_encode($value))); if (!$request->hasHeader('Content-Type')) { $request->setHeader('Content-Type', 'application/json'); } break; default: // Check for custom handler functions. if (isset($this->customOptions[$key])) { $fn = $this->customOptions[$key]; $fn($request, $value); continue; } throw new Iae("No method can handle the {$key} config key"); } } }
/** * @param $data * * @return CookieJar */ public function unserializeCookies($data) { $cookieJar = new CookieJar(); $cookieJar->fromArray(unserialize($data), $this->getDomain()); return $cookieJar; }
/** * @param array $config * * @return array */ protected function addCookiesToForwardDebugSession(array $config) { if (!Config::get(ZedRequestConstants::TRANSFER_DEBUG_SESSION_FORWARD_ENABLED)) { return $config; } if (!isset($_COOKIE[Config::get(ZedRequestConstants::TRANSFER_DEBUG_SESSION_NAME)])) { return $config; } $cookie = new SetCookie(); $cookie->setName(trim(Config::get(ZedRequestConstants::TRANSFER_DEBUG_SESSION_NAME))); $cookie->setValue($_COOKIE[Config::get(ZedRequestConstants::TRANSFER_DEBUG_SESSION_NAME)]); $cookie->setDomain(Config::get(ZedRequestConstants::HOST_ZED_API)); $cookieJar = new CookieJar(); $cookieJar->setCookie($cookie); $config['cookies'] = $cookieJar; return $config; }
/** * Execute the command * * @param Command $command * @return bool */ public function execute(Command $command) { $cookies = CookieJar::fromArray(['TokenKey' => $this->getToken()], $this->hostname); $client = $this->getClient(); // Get the request method $method = $command->getMethod(); // get the url $url = $command->getUrl($this->endpoint); // create the request object with the cookie $this->lastRequest = $client->createRequest($method, $url, $command->getPayload(['cookies' => $cookies])); $this->lastResponse = $client->send($this->lastRequest); $xml = $this->lastResponse->xml(); return isset($xml->Success) && $xml->Success; }
/** * @param RequestInterface $request */ protected function extractCookiesArgument(RequestInterface $request) { $listeners = $request->getEmitter()->listeners('before'); foreach ($listeners as $listener) { if ($listener[0] instanceof Cookie) { $values = []; $scheme = $request->getScheme(); $host = $request->getHost(); $path = $request->getPath(); /** @var SetCookie $cookie */ foreach ($listener[0]->getCookieJar() as $cookie) { if ($cookie->matchesPath($path) && $cookie->matchesDomain($host) && !$cookie->isExpired() && (!$cookie->getSecure() || $scheme == 'https')) { $values[] = $cookie->getName() . '=' . CookieJar::getCookieValue($cookie->getValue()); } } if ($values) { $this->addOption('b', escapeshellarg(implode('; ', $values))); } } } }
public function testCanConvertToAndLoadFromArray() { $jar = new CookieJar(true); foreach ($this->getTestCookies() as $cookie) { $jar->setCookie($cookie); } $this->assertCount(3, $jar); $arr = $jar->toArray(); $this->assertCount(3, $arr); $newCookieJar = new CookieJar(false, $arr); $this->assertCount(3, $newCookieJar); $this->assertSame($jar->toArray(), $newCookieJar->toArray()); }
public function testDeletesCookiesByName() { $cookies = $this->getTestCookies(); $cookies[] = new SetCookie(['Name' => 'other', 'Value' => '123', 'Domain' => 'bar.com', 'Path' => '/boo', 'Expires' => time() + 1000]); $jar = new CookieJar(); foreach ($cookies as $cookie) { $jar->setCookie($cookie); } $this->assertCount(4, $jar); $jar->clear('bar.com', '/boo', 'other'); $this->assertCount(3, $jar); $names = array_map(function (SetCookie $c) { return $c->getName(); }, $jar->getIterator()->getArrayCopy()); $this->assertEquals(['foo', 'test', 'you'], $names); }
/** * Sets up and fills a cookie jar * * @param array $params Request data to fill jar with * @return \GuzzleHttp\Cookie\CookieJar $jar */ private function fillCookieJar(array $params) { $jar = new CookieJar(); $cookies = array(); if (isset($params['cookies'])) { $cookies = array_merge($cookies, $params['cookies']); } $jar->fromArray($cookies, ''); return $jar; }