How do I use Laravel Passport/Sanctum for API auth?

Laravel Passport and Sanctum provide robust solutions for API authentication in Laravel. Passport offers a full OAuth2 server implementation, while Sanctum is simpler and ideal for SPAs and simple token-based APIs. Here's how to use both for API auth:

Using Laravel Passport for API Auth

To use Passport, first, install it via Composer:

composer require laravel/passport

After installation, run the migration to create the necessary tables:

php artisan migrate

Next, register Passport in the AuthServiceProvider:

public function boot() { $this->registerPolicies(); Passport::routes(); }

Configuring API Routes

In your API routes, protect your routes using the auth:api middleware:

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

Using Laravel Sanctum for API Auth

If you prefer a simpler setup, you can use Sanctum:

composer require laravel/sanctum

You can publish the Sanctum configuration and run migrations:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" php artisan migrate

Setting up Sanctum Middleware

Add the Sanctum middleware to your api middleware group within your app/Http/Kernel.php file:

'api' => [ \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ],

Protecting Routes with Sanctum

Use the auth:sanctum middleware to protect your routes:

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

Laravel API Authentication Laravel Passport Laravel Sanctum OAuth2 Token Based Authentication Laravel API