Laravel 11 Passport REST API Authentication Example Tutorial

Laravel 11 Passport REST API Authentication Example Tutorial

Passport is a package that provides OAuth2 server implementation for Laravel 11 applications. It allows developers to easily create REST APIs for authentication in Laravel applications by issuing access tokens and managing their revocation.

Here are the steps to create a REST API using Passport auth via token-based authentication:

Step 1: Install Laravel 11

Start cmd or terminal and run the following command to install laravel 11 setup:

composer create-project --prefer-dist laravel/laravel passportAuth

Step 2: Configure Database

Open .env file and configure database in it; something like this:

 DB_CONNECTION=mysql 
 DB_HOST=127.0.0.1 
 DB_PORT=3306 
 DB_DATABASE=here your database name here
 DB_USERNAME=here database username here
 DB_PASSWORD=here database password here

Step 3: Install Passport Auth

To install passport auth package, use the following command:

cd passportAuth
php artisan install:api --passport

Step 4: Configure Passport Auth

Open user.php model file from App/Models folder and configure passport auth in it; something like this:

<?php

namespace App\Models;

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 HasFactory, Notifiable, HasApiTokens;

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];

/**
* The attributes that should be hidden for serialization.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];

/**
* Get the attributes that should be cast.
*
* @return array
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}

Next open auth.php file from config folder and add api driver in it; something like this:


[
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],

Step 5: Run Migration

To create tables into a database, use the following command:

php artisan migrate

Step 6: Define APIs Route

Open web.php file from routes folder and define authentication routes in it to handle auth requests; something like this:

use App\Http\Controllers\API\PassportAuthController;

Route::post('register', [PassportAuthController::class, 'register']);
Route::post('login', [PassportAuthController::class, 'login']);

Route::middleware('auth:api')->group(function () {
Route::get('get-user', [PassportAuthController::class, 'userInfo']);
});

Step 7: Generate Auth Controller

To generate controller class for authentication, use the following command:

php artisan make:controller Api\PassportAuthController

To handle authentication logic with passport, create some methods in App\Http\Controllers\API\PassportAuthController.php file, like the following:

<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Models\User;
class AuthController extends Controller
{
/**
* Registration Req
*/
public function register(Request $request)
{
$this->validate($request, [
'name' => 'required|min:4',
'email' => 'required|email',
'password' => 'required|min:8',
]);

$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password)
]);

$token = $user->createToken('PassportAuth')->accessToken;

return response()->json(['token' => $token], 200);
}

/**
* Login Req
*/
public function login(Request $request)
{
$data = [
'email' => $request->email,
'password' => $request->password
];

if (auth()->attempt($data)) {
$token = auth()->user()->createToken('PassportAuth')->accessToken;
return response()->json(['token' => $token], 200);
} else {
return response()->json(['error' => 'Unauthorised'], 401);
}
}
public function userInfo()
{
$user = auth()->user();

return response()->json(['user' => $user], 200);
}
}

Step 8: Test Application

To test application, use the following command to start application server:

php artisan serve

You can now test your API endpoints using tools like Postman or cURL. Make sure to include the generated access token in the request headers; something like this:

 'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$accessToken,

]

Conclusion

Congratulations! You’ve successfully set up and made rest API for user authentication using Passport auth in laravel 11.

Recommended Guides

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *