Kritim Yantra
Mar 28, 2025
In this guide, we’ll learn how to:
✔ Set up JWT in Laravel 12
✔ Create login & registration APIs
✔ Protect routes with JWT
✔ Test the API using Postman
By the end, you'll have a fully working JWT authentication system in Laravel!
JWT (JSON Web Token) is a secure way to transmit data between a client (like a React app) and a server (Laravel).
localStorage
). 🔐 Why use JWT?
✅ No need for sessions (stateless)
✅ Works well with mobile apps & SPAs
✅ Secure (signed with a secret key)
composer create-project laravel/laravel laravel-jwt
cd laravel-jwt
php artisan install:api
We’ll use tymon/jwt-auth
, a popular Laravel JWT package.
composer require tymon/jwt-auth
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
php artisan jwt:secret
This adds a JWT_SECRET
key in .env
.
config/auth.php
Change the default guard to api
with JWT driver:
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
Update app/Models/User.php
to implement JWTSubject
:
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
// ...
public function getJWTIdentifier()
{
return $this->getKey(); // Returns user ID
}
public function getJWTCustomClaims()
{
return []; // Extra data in token (optional)
}
}
php artisan make:controller AuthController
Update app/Http/Controllers/AuthController.php
:
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function register(Request $request)
{
$request->validate([
'name' => 'required|string',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password),
]);
$token = Auth::login($user);
return response()->json([
'status' => 'success',
'token' => $token,
'user' => $user,
]);
}
public function login(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (!$token = Auth::attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return response()->json([
'status' => 'success',
'token' => $token,
'user' => Auth::user(),
]);
}
public function user()
{
return response()->json(Auth::user());
}
}
In routes/api.php
:
use App\Http\Controllers\AuthController;
Route::post('register', [AuthController::class, 'register']);
Route::post('login', [AuthController::class, 'login']);
Route::middleware('auth:api')->get('user', [AuthController::class, 'user']);
POST
http://localhost:8000/api/register
{
"name": "John Doe",
"email": "john@example.com",
"password": "password123"
}
✅ Response:
{
"status": "success",
"token": "eyJhbGciOiJIUzI1NiIs...",
"user": { "id": 1, "name": "John Doe", "email": "john@example.com" }
}
POST
http://localhost:8000/api/login
{
"email": "john@example.com",
"password": "password123"
}
✅ Response: Same as register (with a new token).
GET
http://localhost:8000/api/user
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
✅ Response:
{ "id": 1, "name": "John Doe", "email": "john@example.com" }
✅ Solution: Ensure the Authorization
header is correctly formatted:
Authorization: Bearer your_token_here
✅ Solution:
.env
: JWT_TTL=1440 # (in minutes)
✅ Solution: Install fruitcake/laravel-cors
:
composer require fruitcake/laravel-cors
Then enable it in config/cors.php
.
🎉 You’ve successfully set up JWT in Laravel 12!
✔ Installed & configured JWT
✔ Created register/login APIs
✔ Protected routes with JWT middleware
✔ Tested with Postman
Happy coding! 😊🚀
No comments yet. Be the first to comment!
Please log in to post a comment:
Continue with Google