How to Create an API in Drupal with Bearer Token Authentication

Follow this step-by-step guide to create a secure API in Drupal using bearer token authentication with the Simple OAuth module.

1. Install the Simple OAuth Module

First, you need to install the simple_oauth module and its dependencies:

composer require drupal/simple_oauth

Then, enable the module:

drush en simple_oauth -y

2. Configure Simple OAuth

Generate Keys

Simple OAuth requires public and private keys to sign tokens. You can generate these using OpenSSL:

mkdir -p sites/default/files/keys
openssl genrsa -out sites/default/files/keys/private.key 2048
openssl rsa -in sites/default/files/keys/private.key -pubout > sites/default/files/keys/public.key

Ensure these keys are not accessible via the web by updating your .htaccess or web server configuration.

Set Up Simple OAuth

Navigate to /admin/config/people/simple_oauth and enter the paths to your public and private keys.

Create OAuth2 Clients

Navigate to /admin/config/people/simple_oauth/oauth2_client and add a new OAuth2 client with a client ID and secret.

3. Create a Custom Module for API Authentication

Modify the Controller

Edit CustomApiController.php:

<?php

namespace Drupal\custom_api\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\simple_oauth\Authentication\Provider\SimpleOauthAuthenticationProvider;

class CustomApiController extends ControllerBase {
  protected $authProvider;

  public function __construct(SimpleOauthAuthenticationProvider $authProvider) {
    $this->authProvider = $authProvider;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('simple_oauth.authentication.simple')
    );
  }

  public function content(Request $request) {
    $authenticated = $this->authProvider->applies($request) && $this->authProvider->authenticate($request);

    if ($authenticated) {
      $data = [
        'message' => 'Authenticated API response',
        'status' => 'success',
      ];
    } else {
      $data = [
        'message' => 'Access Denied',
        'status' => 'error',
      ];
      return new JsonResponse($data, 403);
    }

    return new JsonResponse($data);
  }
}

Update Permissions

Ensure that the route in custom_api.routing.yml has appropriate permissions:

custom_api.content:
  path: '/api/custom'
  defaults:
    _controller: '\Drupal\custom_api\Controller\CustomApiController::content'
    _title: 'Custom API'
  requirements:
    _permission: 'access content'
  options:
    _auth:
      - bearer
    _format: 'json'

4. Test the API

Obtain a Token

To get a bearer token, send a POST request to /oauth/token with the client credentials:

curl -X POST http://your-drupal-site/oauth/token \
-d "grant_type=password&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&username=YOUR_USERNAME&password=YOUR_PASSWORD"

Access the API

Use the token to access your API endpoint:

curl -X GET http://your-drupal-site/api/custom \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Conclusion

By following these steps, you can secure your Drupal API using bearer token authentication. This setup ensures that only authenticated users can access the API, providing an additional layer of security.

Published By: Krishanu Jadiya
Updated at: 2024-08-06 00:04:50

Card Image

How to Set Up a Local SSL Certificate on Apache: Step-by-Step Guide

Learn how to set up a local SSL certificate on Apache with this comprehensive step-by-step guide. Secure your local development environment with HTTPS.

Card Image

Latest Features of Coding Technology

Explore the latest features and advancements in coding technology, including new programming languages, frameworks, DevOps tools, AI integration, and more.

Card Image

Understanding Laravel Mix Webpack Configuration: Step-by-Step Guide

Step-by-step explanation of a Laravel Mix Webpack configuration file, including asset management for JavaScript, CSS, and Vue.js support.

Card Image

How Emojis Can Enhance Your Git Commits | Gitmoji Guide

Discover how to enhance your Git commits with emojis. Learn about the best practices for creating informative and visually distinctive commit messages.