This lesson will look at Laravel API authentication with Laravel Sanctum and API tokens. To understand how it is used and in what situations, you should read the official documentation.
From the docs:
This feature is inspired by GitHub and other applications which issue "personal access tokens".
Every user of your system would have a personal access token, which they would pass when making API calls.
After creating a new Laravel project and running the migrations, we have a personal_access_tokens
table.
Next, you need to create a token for the user in your application. It could be some action panel on your page, some action on login, or automatically done after registration.
But, to create a token, the HasApiTokens
trait has to be added in a User
Model. It should be done after the install:api
artisan command was executed.
app/Models/User.php:
use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable{ use HasApiTokens, HasFactory, Notifiable; use HasApiTokens; // ...}
Next, you must protect API routes using the auth:sanctum
Middleware. It's the same Middleware we used in the previous lesson for the SPA applications.
routes/api.php:
Route::get('/user', function (Request $request) { return $request->user();})->middleware('auth:sanctum'); Route::apiResource('categories', \App\Http\Controllers\Api\CategoryController::class) ->middleware('auth:sanctum'); Route::get('products', [\App\Http\Controllers\Api\ProductController::class, 'index']);
Now, if we try to access categories without passing any token, we will receive...