Laravel 12 Passport Auth APIs: A Beginner’s Guide

Author

Kritim Yantra

Jun 05, 2025

Laravel 12 Passport Auth APIs: A Beginner’s Guide

Laravel Passport transforms API authentication from a daunting task into a smooth, developer-friendly experience. In this guide, you’ll learn how to set up OAuth2 authentication using Laravel 12 Passport to secure your APIs. No prior OAuth knowledge required!


Why Passport?

Passport provides full OAuth2 server implementation for Laravel. Instead of manually managing API tokens, Passport handles:

  • Access tokens with expiration
  • Refresh tokens
  • Scopes (permissions)
  • Client credential management

Perfect for apps like:
✅ Mobile apps
✅ Single-page applications (SPA)
✅ Third-party API integrations


Step 1: Setup Laravel 12

Prerequisites:

  • PHP 8.2+
  • Composer
  • Database (MySQL, PostgreSQL, etc.)

Create a new Laravel project:

composer create-project laravel/laravel:^12 passport-demo  
cd passport-demo  

Step 2: Install Passport

Install Passport via Composer:

composer require laravel/passport  

Run migrations to create Passport’s tables:

php artisan migrate  

Generate encryption keys (creates OAuth2 tokens):

php artisan passport:install  

Output:

Encryption keys generated successfully.  
Personal access client created successfully.  
Password grant client created successfully.  

Step 3: Configure Passport

A. Register Passport in App\Providers\AppServiceProvider:

use Laravel\Passport\Passport;  

public function boot(): void  
{  
    Passport::hashClientSecrets(); // Securely store client secrets  
    Passport::tokensExpireIn(now()->addDays(15)); // Token expiration  
}  

B. Update config/auth.php:

'guards' => [  
    'api' => [  
        'driver' => 'passport', // Use Passport for API auth  
        'provider' => 'users',  
    ],  
],  

C. Add Traits to App\Models\User:

use Laravel\Passport\HasApiTokens;  

class User extends Authenticatable  
{  
    use HasApiTokens, HasFactory, Notifiable;  
}  

Step 4: Create Authentication APIs

Generate a controller:

php artisan make:controller AuthController  

A. Register API (app/Http/Controllers/AuthController.php):

use App\Models\User;  
use Illuminate\Http\Request;  
use Illuminate\Support\Facades\Hash;  
use Illuminate\Validation\Rules\Password;  

public function register(Request $request)  
{  
    $request->validate([  
        'name' => 'required|string',  
        'email' => 'required|email|unique:users',  
        'password' => ['required', Password::min(8)->mixedCase()->numbers()],  
    ]);  

    $user = User::create([  
        'name' => $request->name,  
        'email' => $request->email,  
        'password' => Hash::make($request->password),  
    ]);  

    return response()->json(['user' => $user], 201);  
}  

B. Login API (Issue Access Token):

use Illuminate\Support\Facades\Auth;  

public function login(Request $request)  
{  
    $credentials = $request->validate([  
        'email' => 'required|email',  
        'password' => 'required',  
    ]);  

    if (Auth::attempt($credentials)) {  
        $user = Auth::user();  
        // Create a personal access token (use createToken('token-name'))  
        $token = $user->createToken('authToken')->accessToken;  
        return response()->json(['token' => $token]);  
    }  

    return response()->json(['error' => 'Invalid credentials'], 401);  
}  

C. Logout API (Revoke Token):

public function logout(Request $request)  
{  
    $request->user()->token()->revoke();  
    return response()->json(['message' => 'Logged out']);  
}  

D. User Profile API (Protected Route):

public function profile(Request $request)  
{  
    return response()->json(['user' => $request->user()]);  
}  

Step 5: Define Routes

Add these to routes/api.php:

use App\Http\Controllers\AuthController;  

Route::post('/register', [AuthController::class, 'register']);  
Route::post('/login', [AuthController::class, 'login']);  

// Protected routes (require valid access token)  
Route::middleware('auth:api')->group(function () {  
    Route::post('/logout', [AuthController::class, 'logout']);  
    Route::get('/profile', [AuthController::class, 'profile']);  
});  

Step 6: Test with Postman

1. Register:

  • URL: POST /api/register
  • Body (JSON):
    {  
      "name": "Alex",  
      "email": "alex@example.com",  
      "password": "Passw0rd!"  
    }  
    

2. Login:

  • URL: POST /api/login
  • Body (JSON):
    {  
      "email": "alex@example.com",  
      "password": "Passw0rd!"  
    }  
    
  • Response:
    { "token": "eyJ0eXAiOiJKV1Q..." }  
    

3. Access Profile:

  • URL: GET /api/profile
  • Header:
    Authorization: Bearer eyJ0eXAiOiJKV1Q...  
    

4. Logout:

  • URL: POST /api/logout
  • Header: Include the same Authorization token.

Troubleshooting Tips

🔹 Token Expiration: Extend expiry in AppServiceProvider using Passport::tokensExpireIn().
🔹 CORS Issues: Allow headers in config/cors.php:

'allowed_headers' => ['*'],  
'allowed_methods' => ['*'],  
'allowed_origins' => ['http://localhost:3000'], // Your frontend URL  

🔹 Missing Scopes: Use tokenCan('scope-name') to check permissions (e.g., read-posts).


Conclusion

You’ve just built a secure API authentication system with Laravel Passport! 🚀 Key takeaways:

  1. Passport simplifies OAuth2 implementation.
  2. Use createToken() to generate access tokens.
  3. Protect routes with the auth:api middleware.

Next Steps:

  • Add password reset flows
  • Implement token refresh
  • Restrict access using scopes

Questions? Let me know in the comments! 👇

LIVE MENTORSHIP ONLY 5 SPOTS

Laravel Mastery
Coaching Class Program

KritiMyantra

Transform from beginner to Laravel expert with our personalized Coaching Class starting June 14, 2025. Limited enrollment ensures focused attention.

Daily Sessions

1-hour personalized coaching

Real Projects

Build portfolio applications

Best Practices

Industry-standard techniques

Career Support

Interview prep & job guidance

Total Investment
$200
Duration
30 hours
1h/day

Enrollment Closes In

Days
Hours
Minutes
Seconds
Spots Available 5 of 10 remaining
Next cohort starts:
June 14, 2025

Join the Program

Complete your application to secure your spot

Application Submitted!

Thank you for your interest in our Laravel mentorship program. We'll contact you within 24 hours with next steps.

What happens next?

  • Confirmation email with program details
  • WhatsApp message from our team
  • Onboarding call to discuss your goals

Tags

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google

Related Posts

Understanding Laravel 12 Middleware
Web Development
Understanding Laravel 12 Middleware
Laravel Php
Kritim Yantra Kritim Yantra
Mar 05, 2025
Install Laravel Breeze Package in Laravel 12
Kritim Yantra Kritim Yantra
Mar 06, 2025