Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, middleware that verifies if the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

Additional middleware can be written to perform a variety of tasks besides authentication. A CORS middleware might be responsible for adding the proper headers to all responses leaving your application.

Code snippet that can be used to implement custom middleware to ban an IP address:

create mymodule.services.yml file: 

services:
  mymodule.custom_middleware:
    class: Drupal\mymodule\CustomMiddleware
    tags:
      - { name: http_middleware, priority: 150 }

create src/CustomMiddleware.php file:

<?php

namespace Drupal\mymodule;

use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * FirstMiddleware middleware.
 */
class CustomMiddleware implements HttpKernelInterface {

    use StringTranslationTrait;

    /**
     * The kernel.
     *
     * @var \Symfony\Component\HttpKernel\HttpKernelInterface
     */
    protected $httpKernel;

    /**
     * Constructs the FirstMiddleware object.
     *
     * @param \Symfony\Component\HttpKernel\HttpKernelInterface $http_kernel
     *   The decorated kernel.
     */
    public function __construct(HttpKernelInterface $http_kernel) {
        $this->httpKernel = $http_kernel;
    }

    /**
     * {@inheritdoc}
     */
    public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
        if ($request->getClientIp() == '127.0.0.1') {
            return new Response($this->t('hello world!'), 403);
        }
        return $this->httpKernel->handle($request, $type, $catch);
    }

}

 

 

Comments

Submitted by Rajeshreeputra (not verified) on Tue, 02/23/2021 - 08:57 Permalink

code not working, custom rest resource does not enter in custom middleware.
Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon