Skip to main content

Welcome to the Drupal Playground!

Hey there, Drupal enthusiasts! 🎉

We’re thrilled to welcome you to Drupal Playground, where creativity, innovation, and the power of Drupal come together. This is your space to explore, learn, and build amazing things using one of the most flexible CMS platforms out there.

Happy Drupaling!
— The Drupal Playground Team

Set Custom Header Variables for API in Drupal 9

  1. Create and Install a Custom Module
  2. Create an Event Subscriber in the Custom Module . Place the Event Subscriber file in the src/EventSubscriber folder of the custom module.
<?php

// In your_module/src/EventSubscriber/CustomHeaderSubscriber.php

namespace Drupal\custom\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpFoundation\Response;

/**
 * Event subscriber to check for a custom header in incoming requests.
 */
class CustomHeaderSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    // Subscribe to the request event, with a priority of 30
    $events[KernelEvents::REQUEST][] = ['checkCustomHeader', 30];
    return $events;
  }

  /**
   * Checks for the presence of a custom header in API requests.
   */
  public function checkCustomHeader(RequestEvent $event) {
    $request = $event->getRequest();

    // Define the name of the custom header to check
    $customHeaderName = 'Custom-Header';
   
    // Check if the request is an API call (URL path starts with '/api/')
    $isApiRequest = strpos($request->getPathInfo(), '/api/') === 0;

    // If it's an API request and the custom header is missing, deny access
    if (!$request->headers->has($customHeaderName) && $isApiRequest) {
        throw new AccessDeniedHttpException('Invalid header token.');
    }
   
    // If it's an API request and the header is present, validate the value
    else if ($isApiRequest) {
        $api_key_value = $request->headers->get($customHeaderName);

        // Check if the custom header value is valid (e.g., '12345')
        if ($api_key_value !== '12345') {
            throw new AccessDeniedHttpException('Invalid header token.');
        }
    }
  }
}


The event subscriber intercepts every request on the site. It first checks if the request is an API call or another type of request. If it's an API request, it validates the custom header value. If the header is valid, the API response is returned. Otherwise, an "Invalid header token" message is returned.

Comments

Popular posts from this blog

Integrating ChatGPT with Drupal 10: A Step-by-Step Guide

  In this blog post, we will guide you through the process of integrating OpenAI’s powerful language model, ChatGPT, into your Drupal 10 website using the OpenAI Contrib module. We'll walk you through the steps of downloading the OpenAI Contrib module (using beta4), setting up an API key from OpenAI, and configuring your Drupal site to use this key for seamless integration. Before you begin, make sure you have an active OpenAI account and have generated your API key from the OpenAI platform. This key will be used to authenticate and allow your Drupal site to interact with the OpenAI service. Steps : 1. Get the latest version of  Open AI  module from the Drupal website and install it on your site.    2.  After installing and enabling the module, navigate to the OpenAI configuration settings and enter your API key.   Generate your OpenAI API key by visiting https://openai.com/api/ .       3.  After configuring the API keys, go to the ...

Drupal Acquia Cloud , DAM and Cloud Hub Interview questions

  What is Acquia Cloud and how is deployment handled there? Acquia Cloud is a managed Drupal hosting platform built on AWS that provides autoscaling, security, CI/CD pipelines, and monitoring tools like Insight and New Relic. Code deployment is Git-based — we push code to the repository, and Acquia pipelines promote the branch to Dev, Stage, or Prod environments. Production is read-only, ensuring controlled deployments.

Drupal Interview Questions

 How to Create a Drupal Multisite?  In multisite, I create separate folders under /sites for each domain, configure individual settings.php with separate databases, and install Drupal per site while reusing the same codebase. Ex : sites/site.domain1/settings.php         sites/site.domain2/settings.php In multisite, even though the codebase is shared, module enablement is stored in each site's configuration. So enable the module only on the required site via admin or drush, and it remains disabled on other sites because they have separate databases. Then you must maintain separate config sync folders per site . $config_directories['sync'] = '../config/site1'; In multisite, apart from settings.php, we use services.yml for service overrides, separate files directories for uploads, private file paths, and most importantly separate config sync directories to isolate configuration per site.