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:
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();
}
In your API routes, protect your routes using the auth:api middleware:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
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
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,
],
Use the auth:sanctum middleware to protect your routes:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?