Format and sign an OAuth / API request

@return string
@ignore
333553
function oAuthRequest($url, $method, $parameters, $multi = false) {

    if (strrpos($url, 'http://') !== 0 && strrpos($url, 'https://') !== 0) {
      $url = "{$this->host}{$url}.{$this->format}";
  }

  switch ($method) {
    case 'GET':
      $url = $url . '?' . http_build_query($parameters);
      return $this->http($url, 'GET');
    default:
      $headers = array();
      if (!$multi && (is_array($parameters) || is_object($parameters)) ) {
        $body = http_build_query($parameters);
      } else {
        $body = self::build_http_query_multi($parameters);
        $headers[] = "Content-Type: multipart/form-data; boundary=" . self::$boundary;
      }
      return $this->http($url, $method, $body, $headers);
  }
  }
479035
private static function signRequest($options = array()) {
    $headers = array();
    $authorizationHeader = "";

    $privateKey = Api::getPrivateKey();
    $keyId = Api::getKeyId();
    $securityBearer = Api::getSecurityBearer();

    if (!empty($privateKey) && !empty($keyId)) {
      $date = date("r");
      array_push($headers, "Date: ".$date);

      $signature = "(request-target): ".strtolower($options["method"])." ".$options["path"]."\n";
      $signature .= "host: ".str_replace("https://", "", Api::getAuthservicesUrl())."\n";
      if (!empty($options["body"])) {
        $digest = base64_encode(hash("sha256", $options["body"], true));
        array_push($headers, "Digest: SHA-256=".$digest);

        $signature .= "content-type: application/json\n";
        $signature .= "content-length: ".strlen($options["body"])."\n";
        $signature .= "digest: SHA-256=$digest\n";
      }
      $signature .= "date: $date";

      openssl_sign($signature, $signedSignature, $privateKey, OPENSSL_ALGO_SHA256);
      $base64SignedSignature = base64_encode($signedSignature);

      $signatureHeaders = "(request-target) host date";
      if (!empty($options["body"])) {
        $signatureHeaders = "(request-target) host content-type content-length digest date";
      }

      $authorizationHeader = "Signature keyId=\"$keyId\", algorithm=\"rsa-sha256\", headers=\"$signatureHeaders\", signature=\"$base64SignedSignature\"";
    } else if (!empty($securityBearer)) {
      $authorizationHeader = "Bearer $securityBearer";
    }

    if (!empty($authorizationHeader)) {
      array_push($headers, "Authorization: $authorizationHeader");
    }

    return array(
      "headers" => $headers
    );
  }
141303
private function buildAuthorizationHeader($oauth)
    {
        $r      = 'Authorization: OAuth ';
        $values = $this->normalizeParameters($oauth);
        $r .= str_replace('&', ', ', $values);

        return $r;
    }
537852
public function get_signable_parameters()
    {
        // Grab all parameters
        $params = $this->parameters;

        // Remove oauth_signature if present
        // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
        if (isset($params['oauth_signature'])) {
            unset($params['oauth_signature']);
        }

        return Twitter_OAuthUtil::build_http_query($params);
    }
635585
public function getSignatureBaseString() {
		$parts = [
			$this->getNormalizedMethod(),
			$this->getNormalizedUrl(),
			$this->getSignableParameters()
		];

		$parts = Util::urlencode( $parts );

		return implode( '&', $parts );
	}
5701
public function getSignature()
    {
        /** @var int $timestamp */
        $timestamp = $this->getTimeStamp();
        $nonceStr  = $this->getnonceStr();
        $ticket    = $this->getTicket();

        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";

        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        /** @var array $signature_array */
        $signature_array              = [];
        $signature_array['appId']     = $this->getAppId();
        $signature_array['nonceStr']  = $nonceStr;
        $signature_array['timestamp'] = $timestamp;
        $signature_array['signature'] = $this->getSignatures($ticket, $nonceStr, $timestamp, $url);

        return $signature_array;
    }
1279964
private function getSignatureMethod(&$request)
    {
        $signatureMethod = @$request->getParameter("oauth_signature_method");
        if (!$signatureMethod) {
            $signatureMethod = "PLAINTEXT";
        }
        if (!in_array(
            $signatureMethod,
            array_keys($this->signatureMethods)
        )
        ) {
            throw new Exception(
                "Signature method '$signatureMethod' not supported " .
                "try one of the following: " .
                implode(", ", array_keys($this->signatureMethods))
            );
        }
        return $this->signatureMethods[$signatureMethod];
    }
247868
protected function createAuthorizationHeader(): string
    {
        $username = $this->getOption('api.username');
        $password = $this->getOption('api.password');

        // The API requires HTTP Basic Authentication, we can't proceed without credentials
        if ($username === null || $password === null) {
            throw new \InvalidArgumentException('Missing credentials for API authentication.');
        }

        return 'Basic ' . \base64_encode("$username:$password");
    }
446201
def signed_uri(with_oauth = true)
      if signed?
        if with_oauth
          params = parameters
        else
          params = non_oauth_parameters
        end

        [uri, normalize(params)] * "?"
      else
        STDERR.puts "This request has not yet been signed!"
      end
    end
876962
public function tokenAction()
    {
        $request = $this->getRequest();
        if (! $request instanceof HttpRequest) {
            // not an HTTP request; nothing left to do
            return;
        }

        if ($request->isOptions()) {
            // OPTIONS request.
            // This is most likely a CORS attempt; as such, pass the response on.
            return $this->getResponse();
        }

        $oauth2request = $this->getOAuth2Request();
        
        $response = $this->server->handleTokenRequest($oauth2request);
        if ($response->isClientError()) {
            $parameters = $response->getParameters();
            $errorUri   = isset($parameters['error_uri']) ? $parameters['error_uri'] : null;
            return new ApiProblemResponse(
                new ApiProblem(
                    $response->getStatusCode(),
                    $parameters['error_description'],
                    $errorUri,
                    $parameters['error']
                )
            );
        }
        return $this->setHttpResponse($response);
    }
1198110
private function generateSignature()
    {
        if (!$this->getPrivateKey()) {
            throw new \Exception('No private key given.');
        }

        $signature = '';
        openssl_sign($this->getCanonizedHeaders(), $signature, $this->getPrivateKey());

        return trim(chunk_split(base64_encode($signature), 73, ' '));
    }
686005
public function get_signature_base_string() {
        $parts = array(
            $this->get_normalized_http_method(),
            $this->get_normalized_http_url(),
            $this->get_signable_parameters()
        );

        $parts = OAuthUtil::urlencode_rfc3986($parts);

        return implode('&', $parts);

    }
1015791
def generate_oauth_signature params, url
      base_request_uri = CGI::escape(url.to_s)
      query_params = []

      params.sort.map do |key, value|
        query_params.push(encode_param(key.to_s) + "%3D" + encode_param(value.to_s))
      end

      query_string = query_params
        .join("%26")
      string_to_sign = "#{@method}&#{base_request_uri}&#{query_string}"

      if !["v1", "v2"].include? @version
        consumer_secret = "#{@consumer_secret}&"
      else
        consumer_secret = @consumer_secret
      end

      return Base64.strict_encode64(OpenSSL::HMAC.digest(digest, consumer_secret, string_to_sign))
    end
551501
function formatUrl(p, callback) {

			// Are we signing the request?
			var sign;

			// OAuth1
			// Remove the token from the query before signing
			if (p.authResponse && p.authResponse.oauth && parseInt(p.authResponse.oauth.version, 10) === 1) {

				// OAUTH SIGNING PROXY
				sign = p.query.access_token;

				// Remove the access_token
				delete p.query.access_token;

				// Enfore use of Proxy
				p.proxy = true;
			}

			// POST body to querystring
			if (p.data && (p.method === 'get' || p.method === 'delete')) {
				// Attach the p.data to the querystring.
				_this.extend(p.query, p.data);
				p.data = null;
			}

			// Construct the path
			var path = _this.qs(p.url, p.query);

			// Proxy the request through a server
			// Used for signing OAuth1
			// And circumventing services without Access-Control Headers
			if (p.proxy) {
				// Use the proxy as a path
				path = _this.qs(p.oauth_proxy, {
					path: path,
					access_token: sign || '',

					// This will prompt the request to be signed as though it is OAuth1
					then: p.proxy_response_type || (p.method.toLowerCase() === 'get' ? 'redirect' : 'proxy'),
					method: p.method.toLowerCase(),
					suppress_response_codes: true
				});
			}

			callback(path);
		}
1262607
public function getSignature(RequestInterface $request, array $params)
    {
        // Remove oauth_signature if present
        // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
        unset($params['oauth_signature']);

        // Add POST fields if the request uses POST fields and no files
        if ($request->getHeaderLine('Content-Type') == 'application/x-www-form-urlencoded') {
            $body = \GuzzleHttp\Psr7\parse_query($request->getBody()->getContents());
            $params += $body;
        }

        // Parse & add query string parameters as base string parameters
        $query = $request->getUri()->getQuery();
        $params += \GuzzleHttp\Psr7\parse_query($query);

        $baseString = $this->createBaseString(
            $request,
            $this->prepareParameters($params)
        );

        // Implements double-dispatch to sign requests
        switch ($this->config['signature_method']) {
            case Oauth1::SIGNATURE_METHOD_HMAC:
                $signature = $this->signUsingHmacSha1($baseString);
                break;
            case Oauth1::SIGNATURE_METHOD_RSA:
                $signature = $this->signUsingRsaSha1($baseString);
                break;
            case Oauth1::SIGNATURE_METHOD_PLAINTEXT:
                $signature = $this->signUsingPlaintext($baseString);
                break;
            default:
                throw new \RuntimeException('Unknown signature method: ' . $this->config['signature_method']);
                break;
        }

        return base64_encode($signature);
    }
248902
protected function clientSignature(Request $request): string
    {
        $signature = '';
        foreach (static::SIGNATURE_HEADERS as $header) {
            $signature .= $request->getHeaderLine($header) . ';';
        }

        return hash('sha256', $signature);
    }
44317
protected function getSignatureMethod(&$request)
    {
        $signature_method =
            @$request->getParameter("oauth_signature_method");
        
        if (!$signature_method) {
            // According to chapter 7 ("Accessing Protected Ressources") the signature-method
            // parameter is required, and we can't just fallback to PLAINTEXT
            throw new OAuthException('No signature method parameter. This parameter is required');
        }
        
        if (!in_array($signature_method,
            array_keys($this->signature_methods))
        ) {
            throw new OAuthException(
                "Signature method '$signature_method' not supported " .
                "try one of the following: " .
                implode(", ", array_keys($this->signature_methods))
            );
        }
        
        return $this->signature_methods[ $signature_method ];
    }