Contents
- Introduction:
- Prerequisite:
- Step 1: Install Laravel 11 Using Composer
- Step 2: Set Database Configuration
- Step 3: Enable API and Install Passport
- Step 4: Update User Model
- Step 5: Update AppServiceProvider.php
- Step 6: Set API Driver Option
- Step 7: Create an Authentication Controller
- Step 8: Create API routes
- Let’s test the API Authentication
Introduction:
Hi! Today we will learn how to create an authentication using laravel passport on our Laravel 11 API. But before that let has a discussion about API and what is Laravel Passport.
API stands for Application Program Interface, API is an interface that allows applications to exchange data. To make it more clear, APIs are a set of functions that can be used by programmers to build software and applications.
Since our API is stateless and doesn’t have a session we will be using the Laravel Passport. It is an Oauth2 server that will be used for API authentication.
Prerequisite:
- Composer
- MySQL
- PHP >= 8.2
Step 1: Install Laravel 11 Using Composer
First, select a folder that you want the Laravel to be installed then execute this command on Terminal or CMD to install Laravel 11:
composer create-project laravel/laravel laravel-11-passport
Install via Laravel Installer:
laravel new laravel-11-passport
Step 2: Set Database Configuration
Open the .env file and set the database configuration:
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your database name(laravel_11_passport)
DB_USERNAME=your database username(root)
DB_PASSWORD=your database password(root)
Step 3: Enable API and Install Passport
By default, laravel 11 API route is not enabled in laravel 11. We will enable the API and install Passport :
php artisan install:api --passport
Step 4: Update User Model
Add the Laravel\Passport\HasApiTokens trait to the App\Modles\User model. The trait provides helper methods for the model to inspect the authenticated user’s token and scopes.
app\Models\User.php
<?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;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}
Step 5: Update AppServiceProvider.php
We won’t be using the passport default routes, we will be creating our custom authentication so we will be removing the default routes. You can check the routes by executing this command: php artisan route:list.
app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Laravel\Passport\Passport;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
Passport::ignoreRoutes();
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}
Step 6: Set API Driver Option
The incoming API request will be authenticated by Passport’s TokenGuard.
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Step 7: Create an Authentication Controller
Now, Let’s create a controller that will be responsible for registering and authenticating users. Run this command:
php artisan make:controller Api/AuthenticationController
then open the AuthenticationController file, and add these codes:
app/Http/Controllers/Api/AuthenticationController.php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
class AuthenticationController extends Controller
{
public function register(Request $request)
{
$formData = [
'name' => $request->name,
'email' => $request->email,
'password' => $request->password,
];
$formData['password'] = bcrypt($request->password);
$user = User::create($formData);
return response()->json([
'user' => $user,
'token' => $user->createToken('passportToken')->accessToken
], 200);
}
public function login(Request $request)
{
$credentials = [
'email' => $request->email,
'password' => $request->password
];
if (Auth::attempt($credentials))
{
$token = Auth::user()->createToken('passportToken')->accessToken;
return response()->json([
'user' => Auth::user(),
'token' => $token
], 200);
}
return response()->json([
'error' => 'Unauthorised'
], 401);
}
}
Step 8: Create API routes
Finally, let’s create a route for the user to register and login.
routes/api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\AuthenticationController;
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:api');
Route::post('register', [AuthenticationController::class, 'register'])->name('register');
Route::post('login', [AuthenticationController::class, 'login'])->name('login');
Let’s test the API Authentication
We will be using Postman for our testing, but you can test it in the way you prefer.
Register
Login
The access token will be used when accessing an API route that needs authentication. Try accessing the /api/user route.
Now our API authentication is done.