Laravel 13 REST API Authentication with Sanctum: Step-by-Step Tutorial
To build a REST API with token authentication in Laravel 13, install Sanctum with php artisan install:api , add the HasApiTokens trait to your User model, issue tokens with createToken() , and protect routes with the auth:sanctum middleware. Clients then send the token as a Bearer header. This guide builds a small login, profile and logout API and shows how to scope tokens with abilities. What do…
To create a REST API with token authentication in Laravel 13, first install Sanctum using the php artisan install:api command. This command publishes the API route file, creates the personal_access_tokens migration, and prepares the app for token authentication. Next, add the HasApiTokens trait to your User model to enable token creation and ownership.
On the login route, validate the user's credentials and password hash. If the credentials are valid, call the createToken() method on the authenticated User instance to generate a token with a specified device name. This method returns a plain-text token that can be returned to the client. Sanctum stores the token as a SHA-256 hash, so the plain-text version is only available once during token creation.
For token logout, simply delete the user's current access token. This clears the token from the user's session, ensuring that the user cannot access protected routes with the expired token.
To protect API routes, use the auth:sanctum middleware within the routes/api.php file. This middleware restricts access to only those requests that present a valid Sanctum token in the Bearer header. By attaching the Sanctum guard to the middleware, you ensure that only authenticated requests with a valid token can access the protected routes.
Token abilities allow for fine-grained access control. When creating a token, you can pass an array of abilities as the second argument to the createToken() method. These abilities act like scopes, restricting access to specific routes or actions based on the token's capabilities. To check if a token has a particular ability, use the tokenCan() method on the user instance or attach a route middleware that verifies the token's ability.
This provides an additional layer of security and flexibility in managing user permissions within the API.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.