Skip to content

Instantly share code, notes, and snippets.

@juampynr
Last active August 6, 2019 08:46
Show Gist options
  • Save juampynr/caf2959c77306f7a299b to your computer and use it in GitHub Desktop.
Save juampynr/caf2959c77306f7a299b to your computer and use it in GitHub Desktop.
Sample Guzzle 6 request to Drupal 8 using OAuth 1

This script helps you to test OAuth-signed requests against Drupal 8.

First, make sure that Drupal has been configured by following the steps at https://www.drupal.org/node/2110825. Then install this script with these steps:

  1. Clone this gist.
  2. Run composer.install.
  3. Open oauth_request.php and fill out your consumer_key and consumer_secret. Then Adjust base_uri.
  4. Execute the script with php oauth_request.php.

NOTE: I had to apply this patch to Guzzle's OAuth Subscriber or authentication would fail.

{
"require": {
"guzzlehttp/guzzle": "~6.0",
"guzzlehttp/oauth-subscriber": "0.3.*"
}
}
<?php
/**
* @file oauthRequest.php
* Performs an OAuth request to retrieve a node.
*/
// Note: the following require is only needed if you want to run this
// code as a standalone script. If you are running this within a Drupal
// environment, then remove the following line, since Drupal does this
// for you already.
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Subscriber\Oauth\Oauth1;
$stack = HandlerStack::create();
$middleware = new Oauth1([
'consumer_key' => 'my-consumer-key',
'consumer_secret' => 'my-consumer-secret',
]);
$stack->push($middleware);
$client = new Client([
'base_uri' => 'http://d8.local',
'handler' => $stack,
]);
// Set the "auth" request option to "oauth" to sign using oauth
$response = $client->get('node/1?_format=json', ['auth' => 'oauth', 'debug' => true]);
$body = $response->getBody();
print_r(json_decode((string) $body));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment