Laravel Airlock - API authentication

Laravel Airlock - API authentication

Laravel Airlock is another laravel official package from Laravel Framework. It's a lightweight authentication package for working on SPA (Single Page Application) or simple API. Before discovering the package, let's have a look at what Laravel Airlock offer us.

Laravel Airlock features

  • Simple API auth
  • Issuing API Tokens
  • Token Abilities
  • Revoking Tokens
  • SPA auth with CSRF protection
  • Authenticating Mobile Applications


Laravel Airlock Installation

Open the command prompt and Install the package by composer require command.

composer require laravel/airlock

Publish the vendor for Laravel Airlock service provider.

php artisan vendor:publish --provider="Laravel\Airlock\AirlockServiceProvider"

Now run the migration command.

php artisan migrate


By default, Laravel offers us auth:api middleware for making simple token-based API authentication. If we use Airlock for API authentication we have to add these on kernel file. So, we can use auth:airlock


use Laravel\Airlock\Http\Middleware\EnsureFrontendRequestsAreStateful;

'api' => [

Done! now you can use Airlock in our API routes.


Laravel Airlock Usages


Route::middleware('auth:airlock')->get('/user', function (Request $request) {
    return $request->user();

We can use multiple guards for authentication. If we use the passport for our API then we have to use like as below

Route::middleware('auth:airlock,passport')->get('/user', function (Request $request) {
    return $request->user();


SPA Authentication

To use SPA auth, first, make a GET request to /airlock/csrf-cookie for enabling the CSRF protection. After that, we have to make a POST request to /login as well as.


API Token Issuing

To issuing API token, we have to use HasApiTokens trait in our user model.

use Laravel\Airlock\HasApiTokens;

class User extends Authenticatable
    use HasApiTokens, Notifiable;

Now we can issue tokens for a user.

$token = $user->createToken('here-token-name');
return $token->plainTextToken;


Token Abilities

We can fix the token abilities for a token so that the user can do only specific thing with that API token.

return $user->createToken('token-name', ['post:update'])->plainTextToken;

To check the ability of a token we can use tokenCan method on a user model object.

if ($user->tokenCan('post:update')) {


Revoking Tokens



Related Post

Laravel Simple Captcha

Laravel Livewire - run php like javascript!

Laravel Log Reader

Laravel Package Development from start to end

Laravel Dusk - automatic app testing package