Building a Simple To-Do App in Laravel
A to-do app is a straightforward way to see how Laravel receives form data, saves it to a database, and displays it…
When a PHP API serves multiple clients, Laravel Passport lets those clients authenticate and receive limited permissions through OAuth 2.0. OAuth 2.0 is a framework for issuing tokens that a client sends whenever it calls a protected endpoint. Because any caller who holds a bearer token can use it, an attacker who steals a token can act with all of its permissions.
Passport issues and validates tokens, and it leaves record-level access decisions to your application. To keep the API secure, you also need to pick the right OAuth flow, shorten token lifetimes, verify permissions on individual records, and protect credentials in transit and in logs. The examples below follow the Laravel 12.x Passport documentation, so check the docs for your own Laravel version before you apply version-specific setup steps.
Use Passport when your API must authorize third-party clients or other consumers that require OAuth 2.0. If you are building a first-party single-page application (SPA), a mobile app, or a straightforward API-token integration, Laravel recommends considering Sanctum instead. Pick the package that matches how your clients authenticate instead of defaulting to Passport for every project.
To call a protected endpoint, a client first obtains an access token through an OAuth flow, which is a sequence of steps for granting access. The client then attaches that token to each request in the Authorization header:
Authorization: Bearer
Your API validates the token before it runs the route handler. Keep tokens out of URLs, because web servers and proxies often write query strings to logs and other systems. Serve the API over HTTPS so the network encrypts credentials and tokens in transit, following the OWASP REST Security Cheat Sheet.
On Laravel 12, install Passport with a single Artisan command:
php artisan install:api --passport
This command publishes and runs migrations for OAuth clients and tokens, creating the database tables that store those records. It also generates the encryption keys Passport uses to sign tokens. Every application instance that issues or validates tokens must have access to those keys.
Next, add Passport’s token support to your User model:
use Laravel\Passport\Contracts\OAuthenticatable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable implements OAuthenticatable
{
use HasApiTokens;
}
Then define an api guard in config/auth.php using the passport driver and your application’s user provider:
'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
This guard tells Laravel to authenticate incoming API requests through Passport. Attach the auth:api middleware to any route that requires an authenticated user:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
When you deploy to an environment that does not yet have encryption keys, run php artisan passport:keys to generate them. Keep private key files out of source control, and supply the matching keys securely to every instance that issues or validates tokens. Check Laravel’s Passport installation and key guidance for version-specific details.
Browser and mobile clients cannot keep a client secret confidential, so have them use Authorization Code with PKCE. With PKCE, the client generates a secret verifier for each authorization request and sends a derived challenge to the server. If someone intercepts the authorization code, they still cannot exchange it for a token without that verifier. Laravel’s documentation specifies a verifier 43–128 characters long and uses the S256 challenge method. Before redirecting the user, the client should also generate and store a state value, then compare it against the returned value to confirm the response belongs to the original request.
When a backend service calls another service on its own behalf, such as a scheduled job, use the Client Credentials grant. Because those requests represent the client application itself and have no end user attached, protect those routes with Passport’s EnsureClientIsResourceOwner middleware instead of auth:api. Mixing the two middlewares blurs the line between user-authenticated requests and machine-to-machine traffic.
Passport 12.x documents the password grant, which trades a user’s password directly for a token. Even though Passport supports it, current OAuth security guidance advises against this grant because it exposes user credentials to the client and breaks down with multi-step authentication. Current guidance also advises against the older implicit grant for new designs. Use a redirect-based authorization flow for user-facing OAuth clients, and review the OWASP OAuth guidance when you pick a flow.
A scope is a named permission that limits what a token can do in general. For example, your API might define an orders-read scope and require it on routes that return order data. Passport includes middleware checks for required scopes, along with middleware for routes that accept any one of several scopes.
Scopes do not control which specific records a user may see. If a user with orders-read swaps in another customer’s order ID in the request, your API still has to verify that the authenticated user owns or may view that record. Enforce those checks with a Laravel policy or an equivalent authorization rule for the target record and action. OWASP classifies missing per-record checks as Broken Object Level Authorization.
Write tests that exercise that boundary directly. Authenticate as one user, request another user’s record by changing the ID, and confirm the API rejects the call. Test each action separately as well, since permission to view an order does not imply permission to update or delete it.
Laravel 12.x Passport sets a default access-token lifetime of one year. That is a long window for a bearer token, because anyone who steals it can use it until it expires or your application revokes it. Passport provides separate configuration methods for access tokens, refresh tokens, and personal access tokens, so set each lifetime based on how sensitive the data is and how easily the client can re-authenticate.
When a user disconnects a client or you suspect a token has been stolen, revoke both the access token and its refresh token. Passport stores expires_at columns in the database for display, and changing a timestamp in the database does not invalidate the token. Use Passport’s revocation methods to cut off access, and run Passport’s purge command on a schedule to clear out revoked and expired token records.
Passport handles authentication, while other controls cover the remaining attack surface. You can attach Laravel route rate limiters to slow down repeated requests, and Laravel returns HTTP 429 when a limit is exceeded. Tailor each limit to what the route does. Token and login endpoints need tight limits to block repeated credential guesses, whereas expensive business operations need limits matched to their resource cost. The Laravel routing documentation shows how to configure rate limiters, and its example numbers are only illustrations; choose thresholds that fit your own traffic.
Validate every incoming payload by type, format, length, and range, and reject unexpected fields. Cap request sizes so a client cannot force your API to process oversized payloads. Restrict cross-origin requests to the specific browser origins that need access, and return generic errors to clients instead of exposing stack traces or internal details.
Log security-relevant events, such as repeated token-validation failures, with enough context to investigate incidents. Keep access tokens, client secrets, passwords, and full credential-bearing requests out of your logs. If you are looking at how to structure your routes as the API grows, see how to organize Laravel routes.
Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.
Take a look at vroni.com