How to Create and Check Custom Header with Middleware for REST API in Laravel?

By Hardik Savani November 5, 2023 Category : Laravel

In Laravel 5 REST API project sometime we need to create create our own custom header for security. like : 'X-hardik':'123456'. this was example, that means in your current project your every request with pass your own custom header like i give you example.this custom header can improve your security. we can also check your header is right or wrong.example :

Your Jquery or AngularJS Request

$.ajax({

type: 'POST',

dataType: 'json',

url: 'http://test.hd/api/login',

headers: { 'X-hardik': '123456'},

data: {'email':'savanihd@gmail.com','password':'123456'}

}).done(function(data){

alert('Login Successfully');

}).fail(function(jqXHR, ajaxOptions, thrownError){

alert(jqXHR.responseText);

});

This is your normal Jquery request with custom header 'X-hardik' and password '123456'.

Now How to check this request in your laravel project.

first fire this command and create middleware.

php artisan make:middleware checkHeader

Ok, now you can check in your project path : app/Http/Middleware/checkHeader.php file

add content on that file.

namespace App\Http\Middleware;

use Closure;

use Illuminate\Contracts\Auth\Guard;

use Response;

class checkHeader

{

/**

* The Guard implementation.

*

* @var Guard

*/

/**

* Handle an incoming request.

*

* @param \Illuminate\Http\Request $request

* @param \Closure $next

* @return mixed

*/

public function handle($request, Closure $next)

{

if(!isset($_SERVER['HTTP_X_HARDIK'])){

return Response::json(array('error'=-->'Please set custom header'));

}

if($_SERVER['HTTP_X_HARDIK'] != '123456'){

return Response::json(array('error'=>'wrong custom header'));

}

return $next($request);

}

}

Now you have to add in app/Http/Kernel.php file for assign middleware name.

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel

{

/**

* The application's global HTTP middleware stack.

*

* @var array

*/

protected $middleware = [

\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,

\App\Http\Middleware\EncryptCookies::class,

\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,

\Illuminate\Session\Middleware\StartSession::class,

\Illuminate\View\Middleware\ShareErrorsFromSession::class,

\App\Http\Middleware\VerifyCsrfToken::class,

];

/**

* The application's route middleware.

*

* @var array

*/

protected $routeMiddleware = [

'auth' =--> \App\Http\Middleware\Authenticate::class,

'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,

'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,

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

];

}

Ok now you can use in your route like this way :

Route::post('api/login', array('uses' => 'APIAuthController@login','middleware' => ['checkHeader']));

Try this...

Tags :
Shares