Laravel Sanctum provides a featherweight authentication system for SPAs, mobile applications, and simple, token-based APIs. It allows each user to generate multiple API tokens for their account, which can be granted specific abilities or scopes.
To protect API routes, use the auth:sanctum middleware. Here’s an example from the project:
routes/api.php
use Illuminate\Http\Request;use Illuminate\Support\Facades\Route;// Protected route - requires authenticationRoute::get('/user', function (Request $request) { return $request->user();})->middleware('auth:sanctum');// Public routes - no authentication requiredRoute::apiResource('institutions', InstitutionsController::class);Route::apiResource('users', UsersController::class);
Currently, most API routes in the project are public and do not require authentication. Consider adding the auth:sanctum middleware to routes that should be protected.
// Protect all routes in the controllerRoute::apiResource('users', UsersController::class) ->middleware('auth:sanctum');// Or protect specific methods in the controller constructorclass UsersController extends Controller{ public function __construct() { $this->middleware('auth:sanctum'); }}
You can assign specific abilities to tokens for fine-grained access control:
// Create token with specific abilities$token = $user->createToken('mobile-app', ['read', 'write'])->plainTextToken;// Create token with all abilities$token = $user->createToken('admin-token', ['*'])->plainTextToken;// Check abilities in controllerpublic function update(Request $request, User $user){ if ($request->user()->tokenCan('write')) { // User has write permission $user->update($request->validated()); }}// Protect routes by abilityRoute::put('/users/{user}', [UsersController::class, 'update']) ->middleware(['auth:sanctum', 'ability:write']);
// Revoke current token (logout)$request->user()->currentAccessToken()->delete();// Revoke all tokens$request->user()->tokens()->delete();// Revoke specific token by ID$request->user()->tokens()->where('id', $tokenId)->delete();
// Get all tokens for the authenticated user$tokens = $request->user()->tokens;// Get token informationforeach ($tokens as $token) { echo $token->name; // Device/app name echo $token->abilities; // Token abilities echo $token->last_used_at; // Last usage timestamp echo $token->created_at; // Creation date}
Display a list of active tokens in your application so users can manage and revoke access from old devices or apps.