Follow these steps to implement authentication using Laravel Sanctum and Laravel Breeze with API scaffolding:
Run the following command to install Laravel Breeze with API scaffolding:
composer require laravel/breeze --dev
php artisan breeze:install api
php artisan migrateOpen app/Models/User.php and add the HasApiTokens trait:
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
}To properly test Laravel Sanctum authentication, follow these setup steps in Postman:
-
Always pass the following header with API requests:
Accept: application/json -
Add a Pre-request Script to handle CSRF token retrieval:
pm.sendRequest({ url: 'http://localhost:8000/sanctum/csrf-cookie', }, function (err, res, {cookies}) { if (err) { console.log("Error fetching CSRF cookie:", err); } else { pm.collectionVariables.set('csrf', cookies.get('XSRF-TOKEN')); } });
-
Include the CSRF token in the request headers:
X-XSRF-TOKEN: {{csrf}}
Upon successful authentication, create and return an API token to the client:
return $user->createToken($request->device_name)->plainTextToken;For protected routes, include the token in the Authorization header:
Authorization: Bearer <your-token>
When logging out, remove all tokens associated with the user:
$request->user()->tokens()->delete();