← Back to Course

Handling API Authentication with Passport or Sanctum

Laravel offers two first-party packages for API authentication: Passport, a full OAuth2 server, and Sanctum, a lighter token-based system built for SPAs, mobile apps, and simple token authentication.

Choosing Between Them

FeatureSanctumPassport
Best forSPAs, mobile apps, simple APIsFull OAuth2 (third-party apps, scopes)
Setup complexityLowHigher
Token typePersonal access tokensOAuth2 access/refresh tokens

Setting Up Sanctum

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

Add the HasApiTokens trait to the User model, then issue a token after login:

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

Protecting Routes

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

Once requests are authenticated, the next concern is usually stopping any single client from overwhelming the API with too many calls.

Ready to master Laravel Training Course?

Join Uncodemy's hands-on Laravel program and build real, production-ready applications.

Explore Course