Laravel 5 : How to create middleware to check custom headers for REST API with example

Laravel 5 : How to create middleware to check custom headers for REST API with example

While creating a REST API we generally need to check headers data, For REST API, headers play vital role to make more secure to the APIs. In this article i am going to tell you how to create middleware to check custom headers for REST API with an example.

For REST API we generally use API token and API key to make secure and for authentication purposes. We send the api key and api token in header. So here we will create a middleware to check these headers that these are available in the requested headers or not, if not then we can restrict to the resquest from accessing to the apis resources.

First thing we will need to create a middleware that will do the desired job for us. Let’s give a name to that middleware. I am giving name as “isAuthorized”. Open your terminal and run the following artisan command if you like this middleware name otherwise you can change as you wish.

php artisan make:middleware isAuthorized

Above artisan command will create a middleware file for you. Class name into this file will be same as the file name itself. You can check this on the following path.

app/Http/Middleware/isAuthorized.php

After that open this newly created middleware file and update it with some piece of code that actually do their work to authorize the incoming request by header checks.

<?php

namespace App\Http\Middleware;

use Closure;

class isAuthorized
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {       
        if(isset(getallheaders()['token']) && getallheaders()['token']=="xxxx") {
            return $next($request);
        }else{
            return response()->json(['status' => false,'error' => "Invalid requst"], 503);
        }
        
    }
}

After creating middleware we will also need to register this middleware to the application’s kernel. So open kernel.php file and add the following line of code to register it.

protected $routeMiddleware = [  
    ...

    'isAuthorized' => \App\Http\Middleware\isAuthorized::class,  

    ...
];

Now this middleware is ready to do their job. But it will not automatically check, we will need to call it in the route group of the application like i mentioned below

Route::group(array('middleware' => ['isAuthorized']), function ()
{
    Route::get('dashboard','HomeController@dashboard');
});