For one of the projects that I have been working on, Drupal is used to manage their employee experience portal. This is one of the core applications for all employees of the company. 

Most of the enterprises are using applications like Active directory to enable their users to access different applications within the wall. Now, even to access employee experience portal, users have to be authenticated using active directory. There are multiple ways of authenticating REST services in Drupal, e.g. cookies based authentication, basic authentication, JWT token authentication, OAuth2.

In the past, they were using custom code to authenticate rest API. So,our Drupal application, which was developed in the past, was also using custom module created for this purpose to authenticate credentials before login via rest.

But we know that every line of custom code adds to the maintenance overhead for the project.

Now, Drupal provides out of the box contributed module to authenticate user details using Oauth2. Oauth  allows users to login to site and authenticate against remote IDP (identity provider) without entering their credentials again.

Below is the example for authenticating Node Rest API. In the same way, we can do for the user as well.

Now you can install and configure this using the following steps -

Step 1

Install the module using Composer: composer config repositories.drupal composer && composer require drupal/simple_oauth:^3

Step 2 :

You can Add your client from here

Then Generate a pair of keys to encrypt the tokens. And store them outside of your document root for security reasons.
openssl genrsa -out private.key 2048
openssl rsa -in private.key -pubout > public.key

1. Save the path to your keys in: /admin/config/people/simple_oauth.
2. Go to REST UI configuration page and enable the oauth2 authentication in your resource.

3. Create a Client Application by going to: /admin/config/services/consumer/add

4. Create a token with your credentials by making a POST request to /oauth/token.Related Document:  the documentation

5. By default module, permissions are set to allow to view only nodes via REST with the authenticated user. If you will request a node via REST without authentication and watch it fail.
6. Request a node via REST with the header Authorization: Bearer {YOUR_TOKEN} and watch it succeed.

In OAuth2, the Protocol is standardized and is honoured by multiple Authorization servers, Clients and Resource servers. And in OAuth2, a single authorization server is sufficient for multiple clients and resources.


Mahaveer Singh

Mahaveer joined Valuebound as fresher and soon proved his calibre by delivering projects with grace. He is working as a Drupal developer but have keen interest in learning new technologies and tools. When not coding or developing awesome Drupal projects he likes to go for rides in his bike or hang out with his friends at Hard Rock Cafe.
More about Mahaveer Singh

comments powered by Disqus