Adding authentication (e.g., OAuth, JWT)for Drupal 8 , 9 , 10 , and 11

Last updated :  

In building a secure and robust system, authentication is paramount. This lesson guides you through adding authentication to your Drupal REST APIs using OAuth 2.0 and JSON Web Tokens (JWT). These methods control access and ensure only verified users or systems can interact with your resources.

Why Use Authentication?

Understanding the importance of authentication is crucial. By implementing authentication, you ensure that only authorized users can access or manipulate your Drupal content via REST APIs. Unauthorized access not only poses security risks but also jeopardizes the integrity of your data.

Implementing OAuth 2.0 in Drupal

OAuth 2.0 is a robust standard for access delegation commonly used in API development. It allows third-party applications to access user data without exposing passwords. To utilize OAuth 2.0 in Drupal, we will leverage the OAuth2 Server module.

Step 1: Install and Configure the OAuth2 Server Module

First, use Composer to install the module:

      
          composer require drupal/oauth2_server
          drush en oauth2_server -y
      
    

Once enabled, configure your OAuth2 server at /admin/config/people/oauth2-server. Create a new client, specifying the client ID, client secret, and API routes it can access. Define the grant types you plan to support, such as authorization code or client credentials.

Step 2: Handle OAuth2 Requests and Endpoints

Ensure your REST endpoints require OAuth2 authentication by configuring permissions and verifying access tokens for incoming requests. This involves modifying your routes defined in my_rest_module.routing.yml:

      
          my_rest_module.get_custom_resource:
            path: '/api/v1/custom-resource/{id}'
            defaults:
              _controller: '\Drupal\my_rest_module\Controller\CustomResourceController::get'
              _title: 'Retrieve Custom Resource'
            requirements:
              _permission: 'use oauth2 token'
              id: \d+
            methods: ['GET']
      
    

This configuration restricts access, allowing only requests bearing valid OAuth2 tokens.

Implementing JWT in Drupal

JSON Web Tokens (JWT) offer another secure way to authenticate your APIs. JWTs are compact, URL-safe tokens that verify user identity effectively. In Drupal, the JWT Authentication module assists in implementing JWT-based authentication.

Step 1: Install and Configure JWT Authentication Module

Install the module using Composer:

      
          composer require drupal/jwt
          drush en jwt -y
      
    

Configuration for JWT occurs under /admin/config/services/jwt. Here, generate or specify your keys, set algorithm preferences, and configure the authentication source.

Step 2: Adjust REST Resource for JWT Authentication

Enable JWT validation checks within your controller to ensure endpoints process valid JWTs:

      
          // File: src/Controller/CustomResourceController.php

          <?php
          namespace Drupal\my_rest_module\Controller;

          use Drupal\Core\Controller\ControllerBase;
          use Symfony\Component\HttpFoundation\JsonResponse;
          use Symfony\Component\HttpFoundation\Request;
          use Drupal\jwt\Authentication\Provider\JwtAuth;

          class CustomResourceController extends ControllerBase {

            protected $jwtAuth;

            public function __construct(JwtAuth $jwt_auth) {
              $this->jwtAuth = $jwt_auth;
            }

            public function get($id, Request $request) {
              // Only proceed if a valid token is found
              $token = $this->jwtAuth->retrieveToken($request);
              if(!$token || !$this->jwtAuth->validateToken($token)) {
                return new JsonResponse(['error' => 'Unauthorized access'], 401);
              }
              
              $data = ['id' => $id, 'name' => 'Sample Resource'];
              return new JsonResponse($data);
            }
          }
      
    

This snippet checks incoming requests for a valid JWT and only processes requests that include verified tokens.

Testing Your Authentication Setup

With OAuth2 and JWT configured, validate your setup by issuing requests through Postman or cURL. Ensure your API checks for and validates authentication tokens before allowing access.

      
          curl -X GET http://yourdrupalsite.com/api/v1/custom-resource/1 -H "Authorization: Bearer "
      
    

Conclusion

Incorporating authentication via OAuth2 and JWT fortifies your APIs with robust security frameworks. These methods ensure that only authorized users can interact with your Drupal resources, safeguarding data integrity and security.

What's Next?

As we continue enhancing our REST API capabilities, the next step is to explore Formatting REST output as JSON. This will help ensure your data is transmitted in a universally understood format, critical for seamless client-server interactions.