Laravel Sanctum

What is Laravel Sanctum?

Laravel Sanctum provides a simple and secure authentication system for APIs and single-page applications (SPAs). It enables token-based authentication while supporting session-based authentication for web applications.


Origin

Sanctum was introduced to simplify API authentication and address the complexities of using OAuth for smaller-scale applications.


Why is it important?

  1. Simplifies API Authentication: Provides an alternative to complex OAuth setups.
  2. Secure Token Management: Issues and revokes personal access tokens easily.
  3. Supports Multiple Use Cases: Handles APIs, SPAs, and traditional web applications.

Best Practices

  1. Use for APIs and SPAs: Sanctum is ideal for applications requiring token-based authentication.
  2. Protect Routes with Middleware: Use Sanctum's middleware to secure API endpoints.
  3. Revoke Expired Tokens: Periodically clear unused or expired tokens.

Example in Action

Install Sanctum:

composer require laravel/sanctum

Publish the configuration:

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

Protect API routes:

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

Issue a token for a user:

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

Laravel Sanctum simplifies secure authentication, making it versatile for modern web applications.