Laravel 12 REST API Authentication with Passport
In this tutorial, you’ll learn how to build a secure REST API in Laravel 12 using Laravel Passport for token-based authentication. We’ll cover everything from installation to testing with Postman.
Prerequisites
Before starting, ensure you have the following:
Step 1: Install Laravel 12 Project
First, create a new Laravel project:
Step 2: Install Laravel Passport
Use Composer to install Passport:
Step 3: Run Migrations
Run the default migrations, which also create Passport tables:
Step 4: Install Passport
This will:
-
Install the latest stable Laravel Passport (
v12.4.2
) -
Downgrade or upgrade conflicting dependencies (like
league/oauth2-server
) to compatible versions -
Resolve the
illuminate/auth
conflict automatically
Then run:
This will finally avoid the $keyPath
error.
Step 5: Add HasApiTokens to User Model
In app/Models/User.php,
Import and use the HasApiTokens
trait:
Step 6: Update API Auth Guard
Open config/auth.php
and update the api
guard:
Step 7: Define API Routes
Open routes/api.php
and define your auth routes:
Step 8: Create the AuthController
Run the command to create a controller:
Step 9: Add Auth Logic in Controller
In app/Http/Controllers/API/AuthenticationController.php
, Add the following:
Step 10: Test API with Postman
Register
-
Method:
POST
-
URL:
http://localhost:8000/api/register
-
Body (raw JSON):
Login
-
Method:
POST
-
URL:
http://localhost:8000/api/login
Access Protected Route
-
Method:
GET
-
URL:
http://localhost:8000/api/get-user
-
Header:
Authorization: Bearer YOUR_ACCESS_TOKEN
Logout
-
Method:
POST
-
URL:
http://localhost:8000/api/logout
(Optional) Handle CORS
If needed, install and configure Laravel CORS:
Then, publish the config and allow origin headers in config/cors.php
.
Conclusion
You’ve successfully built a secure Laravel 12 REST API using Passport. You now have:
-
User Registration
-
Login with Access Token
-
Authenticated API Routes
-
Token-based Logout
Tips
-
Store tokens securely on the client side (e.g., in HTTP-only cookies or secure storage).
-
Use passport:client for password grant and other OAuth flows if needed.
Would you like a downloadable .zip
or ready-to-publish HTML version of this tutorial?