Laravel Airlock feature for API authentication,laravel api authentication with sanctum,api authentication in laravel,laravel authentication for api

Laravel Airlock feature for API authentication

Laravel Airlock feature for API authentication

The Airlock is a new feature in Laravel 7 for API authentication. Airlock provides the simple token base API auth, token issuing, token abilities, revoking tokens, SPA auth with CSRF protection and authentication for mobile applications.

How to install

Open your command prompt and install the package by using composer require command:-


composer require laravel/airlock

Now publish the vendor by using below command for Laravel Airlock service provider.


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

Next, run the migration command.


    php artisan migrate
   

To use Airlock for API authentication we have to add these on kernel file


//kernel.php file

use Laravel\Airlock\Http\Middleware\EnsureFrontendRequestsAreStateful;


'api' => [
    EnsureFrontendRequestsAreStateful::class,
    'throttle:60,1',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

You have completed the configuration, now you can use Airlock in your API’s routes and also middleware auth:airlock like below

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

API Token Issuing

To isse API token, we have to use a trait named HasApiTokens in our user model.


use Laravel\Airlock\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}

Now you can issue a token for a user


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

Token Abilities

You can set the token abilities for a token so a user can do only a specific thing with the API token.


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

SPA Authentication

For SPA Authentication we have to make a GET request to /airlock/csrf-cookie to enable the CSRF protection.

Now make a POST request to /login.

Laravel Airlock feature for API authentication,laravel api authentication with sanctum,api authentication in laravel,laravel authentication for api

Post Created 130

Leave a Reply

Related Posts

Begin typing your search above and press enter to search. Press ESC to cancel.

Back To Top