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. 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.

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

Step 1

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

Step 2 :

You can Add your client from here http://yoursite.com/module/configuration_page

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.

 

Neeraj Kumar

Neeraj is a senior consultant with a proven track record as project manager/ Drupal Architect with a result-oriented drive. He also is a proud new father.
More about Neeraj Kumar

comments powered by Disqus