Drupal 8 – Login in Guzzle Web Service Client @ 1

1. Get your PHP client ready by following my previous post.

 

2. Update your index.php as follow.

<?php
  require 'vendor/autoload.php';
  use Guzzle\Http\Client;
  use Guzzle\Plugin\Cookie\CookiePlugin;
  use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;

  $cookiePlugin = new CookiePlugin(new ArrayCookieJar());
  $client = new Client('http://drupal8.localhost.com');
  
  $client->addSubscriber($cookiePlugin); 
  $request = $client->post('user', null, array(
    'name' => '<username>',
    'pass' => '<password>',
    'form_id' => 'user_login_form',
  ));
  $request->addHeader('Accept', 'application/json');

  $response = $request->send()->json();

  print '<pre>';
  print_r($response);
  print '</pre>';
?>

 

3. Try it out!
drupal-8-web-service-login
 

4. If it works, you can now always use the $client object for all future requests. For example, if you only allow authenticated user to access the content, the following piece of code will return you the corresponding node content.

<?php
  require 'vendor/autoload.php';
  use Guzzle\Http\Client;
  use Guzzle\Plugin\Cookie\CookiePlugin;
  use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;

  $cookiePlugin = new CookiePlugin(new ArrayCookieJar());
  $client = new Client('http://drupal8.localhost.com');
  
  $client->addSubscriber($cookiePlugin); 
  $client->post('user', null, array(
    'name' => '<username>',
    'pass' => '<password>',
    'form_id' => 'user_login_form',
  ))->send();

  $request = $client->get('entity/node/1');
  $request->addHeader('Accept', 'application/json');
  $response = $request->send()->json();

  print '<pre>';
  print_r($response);
  print '</pre>';
?>

 

5. An exception will be thrown without login or the login credential is incorrect.
drupal-8-web-service-login-access-denied
 

Done =)

Reference: Drupal Community – REST: exposing data as RESTful web services

Advertisements

2 thoughts on “Drupal 8 – Login in Guzzle Web Service Client @ 1”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s