What you can do after this lesson
You will let API clients sign in and perform actions as a user, safely. After this lesson, a script can create a Pagelane Books review through the API using a token, and an administrator can see how that token is limited and revoked.
Why tokens, not cookies
A browser keeps the session cookie for you. A script, mobile app or another server has no browser session and no CSRF form. APIs usually use tokens: long random strings the client sends with every request. Laravel's first-party package for this is Sanctum; php artisan install:api in the previous lesson installed it (version 4.4.0 here, as of 2026-11), together with the personal_access_tokens table, and you added the HasApiTokens trait to User. Sanctum also supports cookie-based authentication for single-page apps on the same domain; this lesson covers personal access tokens.
Issuing a token
A route accepts credentials and returns a token. Because it checks passwords, it is rate limited:
Route::post('/tokens', [TokenController::class, 'store'])->middleware('throttle:5,1')->name('tokens.store');public function store(Request $request): JsonResponse
{
$data = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
'device_name' => ['required', 'string', 'max:100'],
]);
$user = User::where('email', $data['email'])->first();
if (! $user || ! Hash::check($data['password'], $user->password)) {
throw ValidationException::withMessages([
'email' => ['These credentials do not match our records.'],
]);
}
$token = $user->createToken($data['device_name'], ['reviews:write']);
return response()->json(['token' => $token->plainTextToken], 201);
}createToken($name, $abilities) stores a row and returns an object whose plainTextToken is the secret to hand to the client. The device_name just labels the token so a user can later recognise and revoke it. The wrong-password branch does not say whether the email exists. Test with curl:
curl -s -H "Accept: application/json" -d "email=reader@example.com&password=password&device_name=curl-demo" http://127.0.0.1:8000/api/tokensHTTP/1.1 201 Created
{"token":"1|<50 random characters>"}The real value is a secret, shown here as a placeholder. It had the shape id|random and 50 characters in total. Keep tokens out of source code, logs and chat. The database never keeps the plain text:
curl-demo | ["reviews:write"] | hash len 64 | App\Models\UserThat is the token's name, abilities, the length of the stored hash (64 characters, a SHA-256 digest) and the owner model. Wrong credentials answered 422 with "These credentials do not match our records.", and a missing field answered 422 with the usual errors object.
Using a token
Protected routes use the auth:sanctum middleware; the client sends the header:
Route::middleware('auth:sanctum')->group(function () {
Route::delete('/tokens', [TokenController::class, 'destroy'])->name('tokens.destroy');
Route::post('/books/{book}/reviews', [ReviewController::class, 'store'])
->middleware('ability:reviews:write')
->whereNumber('book')
->name('books.reviews.store');
});curl -s -H "Accept: application/json" -H "Authorization: Bearer $TOKEN" -d "rating=4&body=Great pacing" http://127.0.0.1:8000/api/books/4/reviewsHTTP/1.1 201 Created
{"data":{"id":7,"rating":4,"body":"Great pacing","reviewer":"Test Reader","created_at":"2026-11-15T08:00:35+00:00"}}(Example captured on 2026-11; the id and time will differ, and $TOKEN holds your token.) The review controller reuses updateOrCreate, so each user has one review per book, and returns the ReviewResource from the previous lesson. The same request without a token answered 401 {"message":"Unauthenticated."}, a rating of 11 answered 422 with "The rating field must be between 1 and 5.", and GET /api/user with the token returned {"id":2,"name":"Test Reader"}.
Abilities
An ability limits what a token can do. This token was created with reviews:write. A second token was created in tinker with only books:read; calling the review route with it returned 403 Forbidden: authenticated, but not allowed. In this fresh Laravel 13 project the first attempt returned 500, because the route used ability:reviews:write and the log said Target class [ability] does not exist. Sanctum's middleware classes are not aliased for you. Register them in bootstrap/app.php:
use Laravel\Sanctum\Http\Middleware\CheckAbilities;
use Laravel\Sanctum\Http\Middleware\CheckForAnyAbility;
$middleware->alias([
'admin' => EnsureUserIsAdmin::class,
'abilities' => CheckAbilities::class,
'ability' => CheckForAnyAbility::class,
]);abilities:a,b requires all of the listed abilities; ability:a,b requires at least one. Abilities are an extra limit on top of policies, not a replacement: a token with reviews:write still acts as that user, so authorization rules still apply.
Revoking and throttling
curl -s -i -X DELETE -H "Accept: application/json" -H "Authorization: Bearer $TOKEN" http://127.0.0.1:8000/api/tokensHTTP/1.1 204 No ContentcurrentAccessToken()->delete() removes the row, and the same token then received 401 Unauthenticated. Users should be able to list and revoke their tokens, and you should delete tokens when a password changes. For throttling, six rapid attempts at the token route gave 422 422 429 429 429 429 (earlier calls in the same minute counted too): after five attempts Laravel answers 429 Too Many Requests until the minute passes. The throttle counters live in the cache store, which is the database here.
Security checklist for token APIs
- Always use HTTPS in production; tokens in plain HTTP can be stolen.
- Show the token once; store only hashes (Sanctum does this).
- Give tokens the fewest abilities needed, and set an expiration (
expirationinconfig/sanctum.php) if your app can live with it. - Return generic login errors and throttle the login route.
- Never log
Authorizationheaders.
Common mistakes
- Forgetting
HasApiTokens, socreateTokendoes not exist. - Not registering the ability aliases, causing a 500 "Target class does not exist".
- Putting the token in the URL. Use the header.
- Sending requests without
Accept: application/jsonand getting redirects instead of JSON errors on web-style failures. - Treating abilities as authorization. Keep policies.
Exercise
Add a DELETE /api/books/{book}/reviews route that deletes the token owner's review for that book, requiring the same ability. Which status would you return when the user has no review there?
Show one possible answer
public function destroy(Request $request, Book $book): JsonResponse
{
$deleted = $book->reviews()->where('user_id', $request->user()->id)->delete();
abort_if($deleted === 0, 404, 'You have no review for this book.');
return response()->json(null, 204);
}Return 204 No Content on success and 404 when nothing was deleted. Add the route inside the auth:sanctum group with ->middleware('ability:reviews:write'). Next: moving slow work out of the request with queues and jobs.
Key points
- Laravel Sanctum issues personal access tokens: the plain text token is shown once, and only a hash is stored in personal_access_tokens.
- Clients send the token in an Authorization Bearer header, and the auth:sanctum middleware identifies the user from it.
- Abilities limit what a token may do; the ability middleware aliases must be registered in bootstrap/app.php in Laravel 13.
- Throttle the endpoint that accepts passwords, and return one generic message for wrong credentials.
- Revoking deletes the current token row, after which the same token receives 401.