Home/Blog/JWT Authentication in Laravel: Step-by-Step Guide with Code
Web Development
JWT Authentication in Laravel: Step-by-Step Guide with Code
AJAjish StephenAugust 7, 20269 min read
JWT (JSON Web Token) authentication is one of the most common ways to secure a Laravel API — especially when the API needs to be consumed by a separate frontend, a mobile app, or a third-party service. This guide walks through the full setup using tymon/jwt-auth, the most widely used JWT package for Laravel, with working code at every step.
Step 1: Install the package
Pull in the package via Composer:
composerrequire tymon/jwt-auth
Step 2: Publish config and generate the secret
Publish the package config, then generate a signing secret:
Add these inside routes/api.php, not routes/web.php — remember the lesson from earlier in this project: routes in api.php get the api middleware group automatically, which JWT relies on for stateless authentication without session/CSRF handling.
Testing it
Test the login endpoint with curl:
curl-X POST http://localhost:8000/api/login \ -H "Content-Type: application/json" \ -d '{"email":"test@example.com","password":"password"}'
A successful response returns an access_token — attach it to future requests as Authorization: Bearer <token>.
Building this into a larger project, or need help structuring an API that will actually scale? This is exactly the kind of work I do as part of web development engagements.
Common questions
Should I use JWT or Laravel Sanctum for API authentication?
Sanctum is the better default for most Laravel apps — it's simpler and built for first-party SPAs and mobile apps talking to your own backend. JWT makes more sense when multiple separate services need to verify a token independently without querying your database, or when you're integrating with a non-Laravel backend that expects standard JWT.
Where should I store the JWT on the client side?
For web apps, an httpOnly cookie is safer than localStorage since it isn't accessible to JavaScript and reduces XSS risk. For mobile apps, secure device storage (Keychain on iOS, Keystore on Android) is the standard approach. Avoid plain localStorage if you can help it.
How long should a JWT token live before expiring?
Short-lived access tokens (15–60 minutes) paired with a longer-lived refresh token is the standard pattern. This limits the damage window if a token is compromised, while the refresh token lets the user stay logged in without re-entering credentials constantly.
Do I need to invalidate JWTs on logout?
Yes, if you want logout to be immediate and secure. JWTs are stateless by design, so a token remains technically valid until it expires unless you explicitly blacklist it. tymon/jwt-auth includes a blacklist feature for exactly this — call it on logout so the token can't be reused even if it's intercepted.
Building an API that needs real authentication?
I build secure, well-structured Laravel APIs for real projects, not just tutorials.