Step-by-Step: Building Secure Laravel APIs with JWT in 2025

Laravel 12 + JWT = secure, scalable APIs for the modern web.
In 2025, API security isn’t just about protecting endpoints—it’s about building trust across mobile apps, SPAs, and microservices. JSON Web Tokens (JWT) offer a stateless, scalable way to authenticate users without relying on sessions or cookies.

This guide walks you through building a secure Laravel API using JWT—from setup to token validation—with code you can copy and deploy.


🔐 Why JWT for Laravel APIs?

  • Stateless authentication: No session storage required
  • Scalable: Perfect for distributed systems and mobile apps
  • Secure: Signed tokens prevent tampering
  • Flexible: Works with Laravel Sanctum, Passport, or custom flows

⚙️ Step 1: Install Laravel & JWT Package

Start with a fresh Laravel 12 project:

laravel new jwt-api
cd jwt-api

Install the JWT Auth package:

composer require tymon/jwt-auth
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
php artisan jwt:secret

This generates a secret key used to sign tokens.


👤 Step 2: Set Up User Authentication

Update your User model to implement JWTSubject:

use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject {
    public function getJWTIdentifier() {
        return $this->getKey();
    }

    public function getJWTCustomClaims() {
        return [];
    }
}

🔑 Step 3: Create Login Endpoint

In AuthController.php:

public function login(Request $request) {
    $credentials = $request->only('email', 'password');

    if (!$token = auth()->attempt($credentials)) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }

    return response()->json(['token' => $token]);
}

This returns a signed JWT token on successful login.


🛡️ Step 4: Protect Routes with Middleware

In routes/api.php:

Route::middleware('auth:api')->group(function () {
    Route::get('/profile', function () {
        return auth()->user();
    });
});

Make sure your config/auth.php uses the JWT driver:

'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

🔄 Step 5: Token Refresh & Logout

Add endpoints to refresh and invalidate tokens:

public function refresh() {
    return response()->json(['token' => auth()->refresh()]);
}

public function logout() {
    auth()->logout();
    return response()->json(['message' => 'Logged out']);
}

🧪 Bonus: Restrict Multiple Device Logins

Use custom claims or token blacklisting to prevent simultaneous logins. This is especially useful for banking, admin panels, or premium content platforms.


✅ Final Thoughts

JWT in Laravel 12 is fast, secure, and production-ready. Whether you’re building mobile apps, SPAs, or microservices, this approach gives you full control over authentication without the overhead of sessions.


References (3)

1Secure Laravel APIs- JWT & OAuth with Passport & Sanctum. https://prateeksha.com/blog/program-geeks-guide-to-building-secure-laravel-apis-with-jwt-and-oauth

2Why Use JWT Authentication in Laravel 12 – LinkedIn. https://www.linkedin.com/pulse/why-use-jwt-authentication-laravel-12-practical-cases-vikash-sharma-lcvkc

3Implementing JWT authentication in Laravel 11 – LogRocket Blog. https://blog.logrocket.com/implementing-jwt-authentication-laravel-11/

Leave a Reply

Your email address will not be published. Required fields are marked *