How to Create and Check Custom Header with Middleware for REST API in 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Use DB Raw Query in Laravel?
- Laravel E-Signature using Docusign API Tutorial
- Get Array of Ids from Eloquent Models in Laravel
- Laravel - How to Upload Picture in Registration Form?
- How to Call External API in Laravel?
- Laravel 9 REST API with Passport Authentication Tutorial
- Laravel 9 REST API Authentication using Sanctum Tutorial
- Laravel Sanctum SPA API Authentication Example
- Laravel Line Chart using Google Charts API Example
- Laravel Mailchimp API Integration Example
- Laravel Storage Dropbox Integration Example
- How to Add Charts in Laravel using Highcharts?
- How to Setup Cron Job in Laravel?