Hello, laravel web developers! In this article, we'll see how to API authentication in laravel 11 using a passport. Here, we'll use laravel passport and create a login and register API in laravel 11. Laravel Passport provides a full OAuth2 server implementation for your Laravel application in a matter of minutes.
API stands for Application Program Interface, API is an interface that allows applications to exchange data.
Laravel 11 API Authentication using Laravel Passport
In this step, we'll install the laravel 11 application using the following command.
composer create-project laravel/laravel laravel-11-example
Next, we'll configure the database into the .env file.
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_11
DB_USERNAME=root
DB_PASSWORD=root
Then, we'll install laravel API using the following command. In laravel by default API is not installed.
php artisan install:api
we'll update the authentication exception of our API middleware. it will not redirect to login but will throw an exception.
bootstrap/app.php
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
//
})
->withExceptions(function (Exceptions $exceptions) {
$exceptions->render(function (AuthenticationException $e, Request $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => $e->getMessage(),
], 401);
}
});
})->create();
Then, we'll install the laravel passport composer package using the following command.
composer require laravel/passport
Now, we'll install a passport using the following command, create an encryption key, and create the necessary tables.
php artisan passport:install
Then, migrate the table into the database using the following command.
php artisan migrate
Then, we'll update the user model and add the HasApiTokens.
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',
];
}
}
Next, we'll update the AppServiceProvider to create our custom authentication. because we'll not use passport default routes.
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
{
//
}
}
Next, we'll define the driver in the auth.php file.
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Then, we'll create a controller using the following command.
php artisan make:controller Api/AuthenticationController
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);
}
}
Then, define API routes into the api.php file
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');
Now, run the laravel 11 application using the following command.
php artisan serve
You might also like:
In today's fast-paced software development landscape, I've understood the significance of continuous integration...
Aug-07-2023
Hello, laravel web developers! In this article, we'll see how to add sweetalert in laravel 11 Livewire. In laravel 1...
May-29-2024
Hello, laravel web developers! In this guide, I’ll walk you through setting up advanced error handling and logging...
Oct-04-2024
In this example we will see example of laravel 8 class numberformatter not found. For numberformatter we need PHP 5...
Dec-27-2021