Exemple #1
0
 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);
 }
Exemple #2
0
 /**
  * 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;
 }
Exemple #3
0
 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);
 }
Exemple #4
0
 /**
  * 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;
 }
 /**
  * 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());
         }
     }
 }
Exemple #6
0
 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");
         }
     }
 }
Exemple #8
0
 /**
  * @param $data
  *
  * @return CookieJar
  */
 public function unserializeCookies($data)
 {
     $cookieJar = new CookieJar();
     $cookieJar->fromArray(unserialize($data), $this->getDomain());
     return $cookieJar;
 }
 public function testCreatesFromArray()
 {
     $jar = CookieJar::fromArray(['foo' => 'bar', 'baz' => 'bam'], 'example.com');
     $this->assertCount(2, $jar);
 }
Exemple #10
0
 /**
  * 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;
 }
Exemple #11
0
 /**
  * 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;
 }
Exemple #12
0
 /**
  * @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;
 }