Laravel 12 REST API Authentication with Passport

Laravel 12 REST API Authentication with Passport

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:

composer create-project laravel/laravel laravel-passport-api

Step 2: Install Laravel Passport

Use Composer to install Passport:

composer require laravel/passport

Step 3: Run Migrations

Run the default migrations, which also create Passport tables:

php artisan migrate

Step 4: Install Passport

composer require laravel/passport:^12.4.2 --with-all-dependencies

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:

php artisan passport:install

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:

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

Step 6: Update API Auth Guard

Open config/auth.php and update the api guard:

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

Step 7: Define API Routes

Open routes/api.php and define your auth routes:

use Illuminate\Support\Facades\Route; Route::group(['namespace' => 'App\Http\Controllers\API'], function () { // --------------- Register and Login ----------------// Route::post('register', 'AuthenticationController@register')->name('register'); Route::post('login', 'AuthenticationController@login')->name('login'); // ------------------ Get Data ----------------------// Route::middleware('auth:api')->group(function () { Route::get('get-user', 'AuthenticationController@userInfo')->name('get-user'); Route::post('logout', 'AuthenticationController@logOut')->name('logout'); }); });

Step 8: Create the AuthController

Run the command to create a controller:

php artisan make:controller API/AuthenticationController

Step 9: Add Auth Logic in Controller

In app/Http/Controllers/API/AuthenticationController.php, Add the following:

namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; class AuthController extends Controller { public function register(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users', 'password' => 'required|min:6', ]); if ($validator->fails()) { return response()->json($validator->errors(), 422); } $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => Hash::make($request->password), ]); $token = $user->createToken('API Token')->accessToken; return response()->json(['token' => $token], 201); } public function login(Request $request) { $credentials = $request->only('email', 'password'); if (!Auth::attempt($credentials)) { return response()->json(['message' => 'Invalid credentials'], 401); } $token = Auth::user()->createToken('API Token')->accessToken; return response()->json(['token' => $token]); } public function user() { return response()->json(Auth::user()); } public function logout(Request $request) { $request->user()->token()->revoke(); return response()->json(['message' => 'Logged out successfully']); } }

Step 10: Test API with Postman

Register

  • Method: POST

  • URL: http://localhost:8000/api/register

  • Body (raw JSON):

{ "name": "StarCode Kh", "email": "starcodekh@gmail.com", "password": "password@123" }

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:

composer require fruitcake/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?

Souy Soeng

Souy Soeng

Our website teaches and reads PHP, Framework Laravel, and how to download Admin template sample source code free. Thank you for being so supportive!

Github

Post a Comment

CAN FEEDBACK
close