Introduction to Laravel 11 API Passport Authentication
Laravel 11 provides a world best framework for building APIs, and Passport is a powerful package that adds OAuth2 authentication to Laravel applications. In this blog post, we will teach how to set up and configure Passport for API authentication step by step for apply seurity in laravel 11.
Installing Passport in Laravel 11
Install Passport package via Composer. Run the following command in your terminal:
composer require laravel/passport
After the installation is complete, you need to run the Passport migrations for storing OAuth2 tokens and clients.
php artisan migrate
Configuring Passport
After complete the migrations , you need to install Passport by running the following command:
php artisan passport:install
After that go to the user model add the name space at the top
import the namespace Laravel\Passport\HasApiTokens
This command generate encryption keys needed to generate secure access tokens. Next, you need to add the
HasApiTokens
full code i attached below to work.
<?php namespace App\Models; // use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Passport\HasApiTokens; class User extends Authenticatable { use HasApiTokens,HasFactory, Notifiable; protected $fillable = [ 'name', 'email', 'password', ];Setting Up Routes for Authentication
To make use of Passport’s authentication routes, you need to add the Passport routes within your AppServiceProvider.php file:
use the namespace
Passport::ignoreRoutes();
Full code here
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Schema; use Laravel\Passport\Passport; class AppServiceProvider extends ServiceProvider { public function register(): void { Passport::ignoreRoutes(); } public function boot(): void { } }
After that you have to go to config/auth.php
file and you should find the guard
and add api passport i have written below .
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Create the Controller using following Command :
php artisan make:controller Api/AuthController
After that go to the controller and open the file AuthController.php
and replace these codes below.
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function register(Request $request)
{
$registerdData = $request->validate([
'name' => 'required|max:55',
'email' => 'email|required|unique:users',
'password' => 'required|confirmed'
]);
$user = User::create($registerdData);
$accessToken = $user->createToken('authToken')->accessToken;
return response(['user' => $user, 'access_token' => $accessToken], 201);
}
public function login(Request $request)
{
$loginData = $request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
]);
if (!auth()->attempt($loginData)) {
return response()->json(['message' => 'Invalid credentials'], 401);
}
$user = auth()->user();
$accessToken = $user->createToken('authToken')->accessToken;
return response()->json([
'user' => $user,
'access_token' => $accessToken,
]);
}
}
you have to install API routing using the install:api
php artisan install:api
implement the routes
api.php replace following code
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\AuthController;
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:sanctum');
Route::post('register', [AuthController::class, 'register']);
Route::post('login', [AuthController::class, 'login']);