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: 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 4: Add HasApiTokens to the 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 5: Update API Auth Guard

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

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

Step 6: Set Up Database

Edit the .env file and configure database details in it:

DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=here your database name here DB_USERNAME=here database username here DB_PASSWORD=here database password here

Step 7: Run Migrations

Run the default migrations, which also create Passport tables:

php artisan migrate

Step 8: Create API Routes

If the a install:api A command is available; run it in your terminal:

php artisan install:api

This will automatically generate API controllers, routes, and configurations, and may also install any

Step 9: 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 10: Create the AuthenticationController

Run the command to create a controller:

php artisan make:controller API/AuthenticationController

Step 11: Add Auth Logic in Controller

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

<?php namespace App\Http\Controllers\API; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Log; use App\Models\User; use Carbon\Carbon; class AuthenticationController extends Controller { /** * Register a new account. */ public function register(Request $request) { $request->validate([ 'name' => 'required|string|min:4', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:8', ]); try { $user = new User(); $user->name = $request->name; $user->email = $request->email; $user->password = Hash::make($request->password); $user->save(); return response()->json([ 'response_code' => 201, 'status' => 'success', 'message' => 'Successfully registered', ], 201); } catch (\Exception $e) { Log::error('Registration Error: ' . $e->getMessage()); return response()->json([ 'response_code' => 500, 'status' => 'error', 'message' => 'Registration failed', ], 500); } } /** * Login request. */ public function login(Request $request) { $request->validate([ 'email' => 'required|email', 'password' => 'required|string', ]); try { if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) { $user = Auth::user(); $accessToken = $user->createToken('authToken')->accessToken; return response()->json([ 'response_code' => 200, 'status' => 'success', 'message' => 'Login successful', 'user_info' => [ 'id' => $user->id, 'name' => $user->name, 'email' => $user->email, ], 'token' => $accessToken, ]); } return response()->json([ 'response_code' => 401, 'status' => 'error', 'message' => 'Unauthorized', ], 401); } catch (\Exception $e) { Log::error('Login Error: ' . $e->getMessage()); return response()->json([ 'response_code' => 500, 'status' => 'error', 'message' => 'Login failed', ], 500); } } /** * Get paginated user list (authenticated). */ public function userInfo() { try { $users = User::latest()->paginate(10); return response()->json([ 'response_code' => 200, 'status' => 'success', 'message' => 'Fetched user list successfully', 'data_user_list' => $users, ]); } catch (\Exception $e) { Log::error('User List Error: ' . $e->getMessage()); return response()->json([ 'response_code' => 500, 'status' => 'error', 'message' => 'Failed to fetch user list', ], 500); } } /** * Logout the user and revoke token. */ public function logOut(Request $request) { try { if (Auth::check()) { Auth::user()->tokens()->delete(); return response()->json([ 'response_code' => 200, 'status' => 'success', 'message' => 'Successfully logged out', ]); } return response()->json([ 'response_code' => 401, 'status' => 'error', 'message' => 'User not authenticated', ], 401); } catch (\Exception $e) { Log::error('Logout Error: ' . $e->getMessage()); return response()->json([ 'response_code' => 500, 'status' => 'error', 'message' => 'An error occurred during logout', ], 500); } } }

Step 12: Personal

To create a personal access client in Laravel, you can use the following Artisan command:

php artisan passport:client --personal

Step 13: Serve the Application

Step 14: Test Routes in Postman

ActionMethodURLAuth Header
RegisterPOSThttp://localhost:8000/api/register-
LoginPOSThttp://localhost:8000/api/login-
Get UserGEThttp://localhost:8000/api/get-userBearer your_token
LogoutPOSThttp://localhost:8000/api/logoutBearer your_token

Step 15: Test the 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

  • Header:
    Authorization: Bearer YOUR_ACCESS_TOKEN

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.

Souy Soeng

Souy Soeng

Hi there 👋, I’m Soeng Souy (StarCode Kh)
-------------------------------------------
🌱 I’m currently creating a sample Laravel and React Vue Livewire
👯 I’m looking to collaborate on open-source PHP & JavaScript projects
💬 Ask me about Laravel, MySQL, or Flutter
⚡ Fun fact: I love turning ☕️ into code!

Post a Comment

CAN FEEDBACK
close