Laravel 10 REST API With Passport Authentication

Laravel 10 REST API With Passport Authentication

 

Laravel 10 REST API With Passport Authentication



In this article, we will see the Laravel 10 REST API with passport authentication. Here, we will learn about how to create REST API in Laravel 10. Also, we will perform CRUD operations with Laravel 10 REST API. REST API is an application program interface that uses HTTP requests to GET, PUT, POST, and DELETE data.

Laravel provides an easy way to create API. If you have authentication in your mobile app then you can easily do it using the passport. Laravel Passport provides a way to create auth tokens for validating users. If your application absolutely needs to support OAuth2, then you should use Laravel Passport.

So, let's see REST API with passport authentication in Laravel 10, Laravel 10 passport API authentication, Laravel REST API example, Laravel passport API authentication, create REST API in Laravel 10 with authentication using passport, and Laravel passport API example.


Step 1: Install Laravel 10

In this step, we will install Laravel 10 using the following command.

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

Step 2: Install Passport Using Composer

Then, We are required to install Passport via the composer package. To get started, install Passport via the Composer package manager.

composer require laravel/passport

After installation of the package, we were required to get default migration to create new passport tables in our database. The Passport migrations will create the tables your application needs to store OAuth2 clients and access tokens. So, run the below command.

php artisan migrate

Now, we will install the passport using the passport:install command, which will create token keys for security. This command will create the encryption keys needed to generate secure access tokens.

php artisan passport:install

Step 2: Passport Configuration

Then, we added API auth configuration in auth.php.

config/auth.php

<?phpreturn [
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',            
        ],
    ],
];

Step 3: Add Table and Model

In this step, we will create a migration of the Product table using the PHP artisan command. So, run the below command in your terminal.

php artisan make:migration User -m

After running the above command you will find migration in this path database/migrations. So, add the below code in your migration file to create a users table.

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('user_id')->nullable();
            $table->string('name')->nullable();
            $table->string('email')->nullable();
            $table->string('date_of_birth')->nullable();
            $table->string('join_date')->nullable();
            $table->string('phone_number')->nullable();
            $table->string('status')->nullable();
            $table->string('two_step')->nullable();
            $table->string('last_login')->nullable();
            $table->string('role_name')->nullable();
            $table->string('avatar')->nullable();
            $table->string('position')->nullable();
            $table->string('department')->nullable();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('users');
    }
};

Now, run the below code in the terminal to create a migration.

php artisan migrate

And add the below code in the User.php file.

<?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 = [
        'user_id',
        'name',
        'email',
        'join_date',
        'last_login',
        'phone_number',
        'status',
        'role_name',
        'email',
        'role_name',
        'avatar',
        'position',
        'department',
        'password',
    ];
    
    /** auto create id */
    protected static function boot()
    {
        parent::boot();
        self::creating(function ($model) {
            $getUser = self::orderBy('user_id', 'desc')->first();

            if ($getUser) {
                $latestID = intval(substr($getUser->user_id, 3));
                $nextID = $latestID + 1;
            } else {
                $nextID = 1;
            }
            $model->user_id = 'KH_' . sprintf("%03s", $nextID);
            while (self::where('user_id', $model->user_id)->exists()) {
                $nextID++;
                $model->user_id = 'KH_' . sprintf("%03s", $nextID);
            }
        });
    }
}

Step 4: Create API Routes

Then, we will create API routes. Laravel provides an api.php file for writing web services routes. So, let's add a route in the api.php file.

routes/api.php

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/
Route::group(['namespace' => 'App\Http\Controllers\Auth'],function()
{
    // ----------------------------login ------------------------------//
    Route::controller(LoginController::class)->group(function () {
        Route::post('login/push', 'authenticate')->name('login/push');
    });

    // ------------------------ register sccount ----------------------//
    Route::controller(RegisterController::class)->group(function () {
        Route::post('register/save','saveRecord')->name('register/save');    
    });
});
Route::group(['namespace' => 'App\Http\Controllers'],function()
{
    // ------------------------- User Management ----------------------//
    Route::controller(UserManagementController::class)->group(function () {
        Route::get('users/list/page', 'index')->middleware('auth:api')->name('users/list/page');
    });
});

RegisterController.php

<?php

namespace App\Http\Controllers\Auth;
use DB;
use Hash;
use Carbon\Carbon;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\Password;
class RegisterController extends Controller
{
    /** page register new */
    public function index()
    {
        return view('auth.register');
    }
    /** save new record */
    public function saveRecord(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email|max:255|unique:users',
        ]);
        try {
            $dt        = Carbon::now();
            $join_date = $dt->toDayDateTimeString();

            $user = new User();
            $user->name         = $request->first_name .$request->last_name;
            $user->email        = $request->email;
            $user->join_date    = $join_date;
            $user->role_name    = $request->role_name;
            $user->password     = Hash::make($request->password);
            $user->save();
            $data = [];
            $data['response_code']  = '200';
            $data['status']         = 'success';
            $data['message']        = 'success Register';
            return response()->json($data);
        } catch(\Exception $e) {
            \Log::info($e);
            $data = [];
            $data['response_code']  = '400';
            $data['status']         = 'error';
            $data['message']        = 'fail Register';
            return response()->json($data);
        }
    }
}

Controller.php

<?php

namespace App\Http\Controllers\Auth;
use DB;
use URL;
use Auth;
use Session;
use Carbon\Carbon;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Http;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */
    use AuthenticatesUsers;
    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

     /** index page login */
     public function login()
     {
         return view('auth.login');
     }
    /** login with databases */
    public function authenticate(Request $request)
    {
        $request->validate([
            'email'    => 'required|string',
            'password' => 'required|string',
        ]);
        try {
            
            $email     = $request->email;
            $password  = $request->password;
            if (Auth::attempt(['email' => $email,'password' => $password])) {

                /** last login updage*/
                $lastUpdate = [
                    'last_login' => Carbon::now(),
                ];
                User::where('email',$email)->update($lastUpdate);
                /** get session */
                $user = Auth::User();
                Session::put('name', $user->name);
                Session::put('email', $user->email);
                Session::put('user_id', $user->user_id);
                Session::put('join_date', $user->join_date);
                Session::put('last_login', $user->last_login);
                Session::put('phone_number', $user->phone_number);
                Session::put('status', $user->status);
                Session::put('role_name', $user->role_name);
                Session::put('avatar', $user->avatar);
                Session::put('position', $user->position);
                Session::put('department', $user->department);
                $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']  = '400';
                $data['status']         = 'error';
                $data['message']        = 'fail Login';
                return response()->json($data);
            }
        } catch(\Exception $e) {
            \Log::info($e);
            $data = [];
            $data['response_code']  = '400';
            $data['status']         = 'error';
            $data['message']        = 'fail Login';
            return response()->json($data);
        }
    }
}

UserManagementController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserManagementController extends Controller
{
    /** index page user list */
    public function index()
    {
        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);
        }
    }
}

Then, we will add the following headers.

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

Register API: Verb: Post, URL:http://127.0.0.1:8000/api/register/save

Login API: Verb: Post, URL:http://127.0.0.1:8000/api/login/push


Get User List API: Verb: get, URL:http://127.0.0.1:8000/api/users/list/page?page=1

That's it! You have successfully installed Laravel on your system.

See you in the next article.

Example project:


Reactions

Post a Comment

0 Comments

close