#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →

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.

Quick Install on Recent Laravel Versions

From Laravel 11 onward, API scaffolding is not included by default. One Artisan command creates routes/api.php, installs Sanctum and publishes its migration:

php artisan install:api

# or, to set up Passport instead of Sanctum
php artisan install:api --passport

The manual steps shown above still work and are what you will see in older projects.

A Complete Token Login Flow

  1. The client sends email and password to a login endpoint.
  2. The server checks the credentials and creates a token.
  3. The client stores the token and sends it in the Authorization: Bearer header.
  4. Protected routes use auth:sanctum to identify the user.
  5. On logout, the current token is deleted so it can no longer be used.
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

Route::post('/login', function (Request $request) {
    $data = $request->validate([
        'email' => 'required|email',
        'password' => 'required',
        'device_name' => 'required',
    ]);

    $user = User::where('email', $data['email'])->first();

    if (! $user || ! Hash::check($data['password'], $user->password)) {
        throw ValidationException::withMessages(['email' => 'Invalid credentials.']);
    }

    return ['token' => $user->createToken($data['device_name'], ['orders:read'])->plainTextToken];
});

Route::middleware('auth:sanctum')->post('/logout', function (Request $request) {
    $request->user()->currentAccessToken()->delete();
    return response()->noContent();
});

Limiting What a Token Can Do

The second argument to createToken lists abilities. Check them in code before performing sensitive actions:

if ($request->user()->tokenCan('orders:read')) {
    return $request->user()->orders;
}
abort(403);

Passport offers the same idea through OAuth2 scopes, which also appear on the consent screen when a third-party app requests access.

Give each token only the abilities its client needs. A reporting script that only reads orders should not receive a token that can delete them, so a leaked token does far less damage.

SPA Cookie Mode Versus Tokens

If your Vue or React front end is served from the same top-level domain as the API, Sanctum can authenticate it with Laravel's normal session cookie instead of tokens. The SPA first calls /sanctum/csrf-cookie, then logs in through a regular login route. List the front-end domain in the SANCTUM_STATEFUL_DOMAINS setting and allow credentials in your CORS configuration. This avoids keeping long-lived tokens in browser storage.

Mobile apps and external scripts cannot share cookies, so they use the token flow shown earlier.

Safe Defaults Checklist

  • Serve the API only over HTTPS so tokens are never sent in plain text.
  • Set a token expiry through the expiration option in config/sanctum.php, and prune old tokens on a schedule.
  • Throttle the login route to slow down password guessing.
  • Give each device its own named token so a lost phone can be revoked alone.
  • Choose Passport only when you truly need OAuth2, such as letting outside developers build apps on your platform.
  • Return the plain-text token only once, at creation. Sanctum stores a hash of it, so it cannot be shown again; ask the user to create a new one if it is lost.

Ready to master Laravel Training Course?

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

Explore Course