Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Passport REST API Authentication Example

Last Updated on April 23, 2024 by

In Laravel 11, Passport Auth package allows users to create login, register REST API by token based authentication.

Let’s start installing and configuring Passport auth to create token based authentication:

Step 1 – Install Laravel and Create a New Project

Run the following composer command to install and create new laravel project:

composer create-project --prefer-dist laravel/laravel passport-auth-example

Step 2: Install Laravel Passport

Install passport auth to create rest api:

cd passport-auth-example
php artisan install:api --passport

Step 3 – Configure Passport

Edit your user.php model from app/models folder, and add the HasApiTokens trait:

use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    // Rest of your model code...
}

Edit config/auth.php file and API driver:

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

Step 4 – Set Up Database

Edit .env file and configure database details in it:

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

Run migration command to create tables into your configured database:

php artisan serve

Step 5 – Create API Routes

Next, define the routes for your API endpoints. Open your api.php file located at routes/api.php and define your routes:

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 6 – Create Controller and Method

Create a controller file by using the following command:

php artisan make:controller Api\PassportAuthController

Now implement authentication methods into it to handle login, registration and user detail functionality from database:

<?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 7 – Test

Run artisan serve command to start the application server:

php artisan serve

And open Postman application and call these API for testing:

Register a User:

  1. Open Postman.
  2. Set the request type to POST.
  3. Enter http://yourdomain.com/api/register in the address bar (replace yourdomain.com with your actual domain).
  4. Go to the Body tab.
  5. Choose x-www-form-urlencoded and select JSON.
  6. Enter the user registration data in JSON format, including name, email, and password.
  7. Click on the Send button to register the user.

Login:

  1. Set the request type to POST.
  2. Enter the URL of your Laravel application followed by /api/login (e.g., http://yourdomain.com/api/login).
  3. Go to the Body tab.
  4. Select x-www-form-urlencoded and set the format to JSON.
  5. Enter the user’s credentials (email and password) in JSON format.
  6. Click on the Send button to login. You will receive a token in the response if the login is successful.

Get User Info:

  1. Set the request type to GET.
  2. Enter the URL of your Laravel application followed by /api/get-user (e.g., http://yourdomain.com/api/get-user).
  3. Go to the Headers tab.
  4. Add a new header with the key Authorization and the value Bearer <token>, where <token> is the token obtained during the login process.
  5. Click on the Send button to get the user information.

Leave a Comment