Laravel 11 Passport REST API Authentication Example

Laravel 11 Passport REST API Authentication Example

Laravel 11 Passport REST API Authentication Example

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

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



Prerequisites:

* Git: Git is a version control system used for tracking changes in source code during software development. Make sure Git is installed on your system. You can download Git from https://git-scm.com/ and follow the installation instructions for your operating system.

* PHP: Laravel requires PHP to be installed on your system. You need PHP version 7.3 or higher. You can check your PHP version by running php -v in your terminal.
* Composer: Composer is a dependency manager for PHP and is used to install Laravel and its dependencies. You can download Composer from https://getcomposer.org/ and follow the installation instructions for your operating system.
* Web Server: You'll need a web server to serve your Laravel application. While Laravel comes with a built-in development server, it's recommended that Apache or Nginx be used for production deployments.
* Database: If the cloned project uses a database, make sure you have the required database management system (e.g., MySQL, PostgreSQL, SQLite) installed on your system. 

* Postman: is an API platform for building and using APIs. Postman simplifies each step of the API lifecycle and streamlines collaboration so you can create better APIs faster. Can download https://postman.com/ 

Step 1 – Install Laravel and Create a New Project

Run the following composer command to install and create a 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:

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 the .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

Step 5 – Migrate Database:

Run the database migrations to create the necessary tables in your database:

php artisan migrate

Step 6 – 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:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\AuthController;

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

Step 7 – Create Controller and Method

Create a controller file by using the following command:

php artisan make:controller API/AuthController

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

<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Models\User;
use Carbon\Carbon;
use Auth;
use Hash;

class AuthController extends Controller
{
    /** register new account */
    public function register(Request $request)
    {
        $request->validate([
            'name'     => 'required|min:4',
            'email'    => 'required|email',
            'password' => 'required|min:8',
        ]);
 
        $dt        = Carbon::now();
        $join_date = $dt->toDayDateTimeString();

        $user = new User();
        $user->name         = $request->name ;
        $user->email        = $request->email;
        $user->password     = Hash::make($request->password);
        $user->save();

        $data = [];
        $data['response_code']  = '200';
        $data['status']         = 'success';
        $data['message']        = 'success Register';
        return response()->json($data);
    }

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

        try {

            $email     = $request->email;
            $password  = $request->password;

            if (Auth::attempt(['email' => $email,'password' => $password])) 
            {
                $user = Auth::User();
                $accessToken = $user->createToken($user->email)->accessToken;
    
                $data = [];
                $data['response_code']  = '200';
                $data['status']         = 'success';
                $data['message']        = 'success Login';
                $data['user_infor']     = $user;
                $data['token']          = $accessToken;
                return response()->json($data);
            } else {
                $data = [];
                $data['response_code']  = '401';
                $data['status']         = 'error';
                $data['message']        = 'Unauthorised';
                return response()->json($data);
            }
        } catch(\Exception $e) {
            \Log::info($e);
            $data = [];
            $data['response_code']  = '401';
            $data['status']         = 'error';
            $data['message']        = 'fail Login';
            return response()->json($data);
        }
    }

    /** user info */
    public function userInfo() 
    {
        try {
            $userDataList = User::latest()->paginate(10);
            $data = [];
            $data['response_code']  = '200';
            $data['status']         = 'success';
            $data['message']        = 'success get user list';
            $data['data_user_list'] = $userDataList;
            return response()->json($data);
        } catch(\Exception $e) {
            \Log::info($e);
            $data = [];
            $data['response_code']  = '400';
            $data['status']         = 'error';
            $data['message']        = 'fail get user list';
            return response()->json($data);
        }
    }
}

Step 8 – Personal

To create a personal access client in Laravel, you can use the following Artisan command:

php artisan passport:client --personal

Step 9 – Test

Run the artisan serve command to start the application server:

php artisan serve

  1. Open the 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 nameemail, 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 log in. 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.

Reactions

Post a Comment

0 Comments

close