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.
1. Install Laravel Project
composer create-project laravel/laravel laravel-passport-api
2. Install Package Passport to laravel
composer require laravel/passport
After the installation is complete, you need to run the Passport migrations for storing OAuth2 tokens and clients.
2.1 Preblem Solve to install this require package need to enable extension in php.ini
php artisan migrate
4. Configuring Passport
php artisan install:api --passport
5. Configure User Model
use Laravel\Passport\HasApiTokens;
add HasAipTokens in class User
HasApiTokens
6. Configure App Service Provider
use Laravel\Passport\Passport;Passport::ignoreRoutes();
7. Configure API Auth
'api' => ['driver' => 'passport','provider' => 'users',],
8. Create API Controller
php artisan make:controller Api/AuthController
9. Configure file AuthController.php
After that go to the controller and open the file AuthController.php and replace these codes below.
<?phpnamespace 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,]);}}
10. Install API to Laravel
you have to install API routing using the install:api
php artisan install:api
11. Implement API Rout
implement the routes api.php replace following code
use App\Http\Controllers\Api\AuthController;
Route::post('register', [AuthController::class, 'register']);
Route::post('login', [AuthController::class, 'login']);