Drupal 8 restful API oauth 2

Edward Ziadeh • 19 February 2019
Blog in group Drupal 8
0 comments
0 likes

How to use OAuth 2 with drupal 8?

I'm going to explain in this tutorial how to use a username and password for a user that already registered.
The user will connect from a third party app, "website, IOS app, Android or any other app". 

On this little tutorial I'm going to show you how to create a Bearer Token and a refresh token.

Step 1
Let's start with enabling the rest API and I recommend to install the REST UI module.

Step2
Install the Simple OAuth module and enable it, to enable the OAuth module you also need to install Consumers module.

Step 3
After we enabled all of the required modules, we need to create a role that give the user who hold it a permission to create the token, also gives the permission to use other functions like:

  • Create a new post
  • view pages
  • delete comments
  • etc

To do so and after we created the role we need to create UUID to do this go to:

  • Admin
  • Configuration
  • Web Services
  • Consumers

admin config web services consumers

Before we create the consumer client uuid we need to go to the settings and create a public and private key.
Drupal 8 Generate a public and private key

After that click the add consumer button and fill the form. At the end of the form use the role as a scope.
Drupal 8 api scope

Step 4
I will use the post man to create a token for one of my users.

  • url link : https://{{domain}}/oauth/token?_format=json
  • Method Post
  • header
    • key - content-type
    • value - application/json
  • Body
    • username
    • password
    • client_id
    • secret_id
    • grant_type
      • password

Postman drupal 8 oauth create token

The response will be like this.
Drupal 8 oauth token response

Now you can this token to create delete or what ever you give a permission for the role that hold the scope.

Thanks and I hope that it will help someone out there :).

JQuery Ajax code:

var form = new FormData();
form.append("username", "test");
form.append("password", "123456");
form.append("client_id", "becfd6e0-fa1d-4cc2-9c18-bcd68bbe11a5");
form.append("client_secret", "abc123");
form.append("grant_type", "password");

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://domain.test/oauth/token?_format=json",
  "method": "POST",
  "headers": {
    "Content-Type": "application/x-www-form-urlencoded",
    "cache-control": "no-cache",
    "Postman-Token": "d0282a9f-1d61-4740-8fc7-5e06572a17ac"
  },
  "processData": false,
  "contentType": false,
  "mimeType": "multipart/form-data",
  "data": form
}

$.ajax(settings).done(function (response) {
  console.log(response);
});