Friday, November 29, 2019

How to create custom middleware to check custom header for REST API in Laravel 5


In this Laravel 5 PHP Tutorial, I will let you know how to create our own custom middleware to check custom header for the security.
For example, if you want to check whether security key/token exists in the header or not. you can restrict your apis using middleware with some checks.
You need to first create a custom middleware "isAuthorized" by running below artisa command in your application.
php artisan make:middleware isAuthorized
Ok, now you can check in your project path : app/Http/Middleware/isAuthorized.php file
isAuthorized Middleware
<?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);
        }
        
    }
}
Now I will add this custom middleware in app/Http/Kernel.php file for assign middleware name.
    protected $routeMiddleware = [  
        ...

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

        ...
    ];  
Now you can create a group to apply filters on group of routes instead of specifying the filter on each route, as group allow us to use middleware, namespace etc.
Route::group(array('middleware' => ['isAuthorized']), function ()
{
    Route::get('dashboard','HomeController@dashboard');
});





Load disqus comments

0 comments