Hi there! I’m excited to share my journey of setting up secure API authentication using Laravel 12 and Laravel Passport. If you’re a developer looking to build robust APIs, Laravel 12 makes it super easy with its elegant syntax and powerful tools.
Laravel Passport, an OAuth2 server implementation, simplifies token-based authentication, ensuring your APIs are secure and scalable.
In this guide, I’ll walk you through the process step-by-step, sharing practical tips and code snippets to help you master Laravel 12 authentication.
Before we get started, let’s talk about why Laravel Passport is a great choice for Laravel 12 authentication:
This article will guide you through setting up Laravel Passport, securing API routes, and managing tokens effectively, all while focusing on Laravel 12 authentication.
Here’s a detailed, beginner-friendly guide to setting up API authentication in Laravel 12 using Laravel Passport. Follow along, and you’ll have a secure API in no time!
First, ensure you have Composer installed. Then, create a new Laravel 12 project:
composer create-project --prefer-dist laravel/laravel laravel-passport-auth
cd laravel-passport-auth
Configure your database in the .env
file:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_passport
DB_USERNAME=root
DB_PASSWORD=
Run migrations to set up the default database tables:
php artisan migrate
Install Laravel Passport using Composer:
composer require laravel/passport
Next, run the install:api
Artisan command to publish Passport’s migrations and generate encryption keys:
php artisan install:api
This command creates tables for OAuth2 clients and tokens and generates oauth-public.key
and oauth-private.key
for secure token issuance.
Add the HasApiTokens
trait to your User
model (app/Models/User.php
) to enable token management:
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
protected $fillable = ['name', 'email', 'password'];
}
Update the config/auth.php
file to use Passport’s TokenGuard
for API authentication:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Let’s create a custom AuthController
to handle registration and login. Generate the controller:
php artisan make:controller AuthController
Add the following code to app/Http/Controllers/AuthController.php
:
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function register(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
]);
$user = User::create([
'name' => $validated['name'],
'email' => $validated['email'],
'password' => Hash::make($validated['password']),
]);
$token = $user->createToken('auth_token')->accessToken;
return response()->json(['token' => $token], 201);
}
public function login(Request $request)
{
$credentials = $request->validate([
'email' => 'required|email',
'password' => 'required',
]);
if (auth()->attempt($credentials)) {
$token = auth()->user()->createToken('auth_token')->accessToken;
return response()->json(['token' => $token], 200);
}
return response()->json(['error' => 'Unauthorized'], 401);
}
}
Define API routes in routes/api.php
:
<?php
use App\Http\Controllers\AuthController;
use Illuminate\Support\Facades\Route;
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
Route::middleware('auth:api')->group(function () {
Route::get('/user', function () {
return auth()->user();
});
});
The auth:api
middleware protects routes, ensuring only authenticated users with valid tokens can access them. Test the /user
route by sending a GET request with the Authorization: Bearer <token>
header.
Use a tool like Postman to test your API:
/api/register
with name
, email
, and password
./api/login
with email
and password
./api/user
with the token in the Authorization
header.Example Postman request for login:
http://localhost:8000/api/login
{
"email": "[email protected]",
"password": "password123"
}
You’ll receive a JSON response with an access token if successful.
Laravel Passport supports token revocation and refresh tokens. To revoke a token (e.g., for logout), add a logout method to AuthController
:
public function logout(Request $request)
{
$request->user()->token()->revoke();
return response()->json(['message' => 'Logged out successfully'], 200);
}
Add the route in routes/api.php
:
Route::middleware('auth:api')->post('/logout', [AuthController::class, 'logout']);
oauth-public.key
and oauth-private.key
.
Setting up API authentication in Laravel 12 with Laravel Passport is straightforward and powerful. By following this guide, you’ve learned how to install Passport, configure your application, secure API routes, and manage tokens effectively.
Laravel 12 authentication with Passport ensures your APIs are secure, scalable, and compliant with OAuth2 standards. Whether you’re building a mobile app or a web platform, Passport simplifies the process, letting you focus on creating amazing features. Start implementing these steps today, and take your Laravel development to the next level!
Laravel Passport is an OAuth2 server implementation for Laravel. It enables secure, token-based API authentication and simplifies access token management.
Passport is ideal for full OAuth2 support in complex APIs. Sanctum is simpler and better suited for SPAs or mobile apps needing basic token auth.
Use the refresh_token
grant type. Send a POST request to /oauth/token
with the necessary parameters to obtain a new access token.
Yes, Laravel Passport is fully compatible with Laravel 12 and provides advanced API authentication tools out of the box.
Use auth:api
middleware, enforce HTTPS, validate all input, limit token scopes, and apply throttle middleware to reduce abuse.
You might also like: