Laravel 10 Restful API Passport Authentication Tutorial

  • 21-02-2023
  • 2336
  • Laravel 10
  • Haresh Chauhan

Watch Youtube Video (HINDI) :

In this tutorial we will see Laravel 10 Restful API Passport Authentication, In Laravel 10 Passport we will integrate and show you how to generate token and authentication API in the laravel 10 application.

This tutorial will help you to integrate Laravel 10 API Authentication using passport, also in this post, I have included a youtube video for more understanding of how to integrate passport in laravel 10 latest version.

So if you want to authenticate API using passport laravel 10 this post content will help you from scratch to advance your level of understanding of passport authentication.

By default laravel not included the laravel passport package in the app, we need to add and customize it according to our use in laravel 10 and need to install composer "laravel/passport" for getting core libraries.

Laravel 10 Restful API Passport Authentication Steps :

  • Step 1. Clone New Project
  • Step 2. Database Config
  • Step 3. Install Passport
  • Step 4. User Model Config
  • Step 5. Config Auth Guard
  • Step 6. Make UserController
  • Step 7. Route Define
  • Step 8. Make User Seeder
  • Step 9. Start Development Server
  • Step 10. Preview

Step 1. Clone New Project

First, we will install laravel 10 new fresh project just by using the below command in your terminal, before that you need to install composer in your system as well as apache server and MySQL database server for the support PHP 8.2 version.

composer create-project laravel/laravel example-app

Step 2. Database Config

After that we will config the laravel, goto .env file, this file you will see at the root of the project. go to the database and create a database and then add configuration here for the connection laravel app with the database.

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Step 3. Install Passport

In this step, we will install the composer package, use the given suggested command and paste it into your project terminal and install the passport library in the app.

composer require laravel/passport

After that, we will migrate all our app database tables in the database using the given command. you will see it in the database passport migration also.

php artisan migrate

Once we successfully migrate tables, we will install a passport for the generated token in the laravel 10 app. use the given command, this command will generate the client id and some keys for the use of passport services.

php artisan passport:install

Step 4. User Model Config

By default laravel provides sanctum API authentication, which we need to replace, use Laravel\Passport\HasApiTokens; add this line as below given example code and use in the mode.

<?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; // ADD THIS
    
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}

Step 5. Config Auth Guard

Now time to add a guard for the user table in the guards attribute at the config/auth.php file.

config/auth.php
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [                        // ADD THIS
            'driver' => 'token',          // ADD THIS
            'provider' => 'users',        // ADD THIS
            'hash' => false,              // ADD THIS
        ],                                // ADD THIS
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,
];

Step 6. Make UserController

Create a UserController using the suggested command.

php artisan make:controller UserController

After creating UserController, just copy given the code and paste it into your UserController. In this controller, we have to define authentication, log out, and get user method.

App\Http\Controllers\API\UserController.php
<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Auth;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function loginUser(Request $request): Response
    {
        $input = $request->all();

        Auth::attempt($input);

        $user = Auth::user();

        $token = $user->createToken('example')->accessToken;
        return Response(['status' => 200,'token' => $token],200);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function getUserDetail(): Response
    {
        if(Auth::guard('api')->check()){
            $user = Auth::guard('api')->user();
            return Response(['data' => $user],200);
        }
        return Response(['data' => 'Unauthorized'],401);
    }

    /**
     * Display the specified resource.
     */
    public function userLogout(): Response
    {
        if(Auth::guard('api')->check()){
            $accessToken = Auth::guard('api')->user()->token();

                \DB::table('oauth_refresh_tokens')
                    ->where('access_token_id', $accessToken->id)
                    ->update(['revoked' => true]);
            $accessToken->revoke();

            return Response(['data' => 'Unauthorized','message' => 'User logout successfully.'],200);
        }
        return Response(['data' => 'Unauthorized'],401);
    }
}

Step 7. Route Define

Add routes in your api.php route file, this file is located in "routes/api.php". you can copy the given route file and paste the code given in the example.

routes/api.php
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\UserController;
/*
|--------------------------------------------------------------------------
| 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::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::controller(UserController::class)->group(function(){
    Route::post('login','loginUser');
});

Route::controller(UserController::class)->group(function(){

    Route::get('user','getUserDetail');
    Route::get('logout','userLogout');

})->middleware('auth:api');

Step 8. Make User Seeder

We will make a seeder for the generate dummy data in the database user table. just copy the run() method code and paste it into your database seeder file.

database/seeders/DatabaseSeeder.php
<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // \App\Models\User::factory(10)->create();

        \App\Models\User::factory()->create([
            'name' => 'Admin User',
            'email' => 'admin@gmail.com',
            'password' => bcrypt(123456),
        ]);
    }
}

After that, we will press a command the see seeder data in the database. use suggested commands and seed use data in the database.

php artisan db:seed

Step 9. Start Development Server

Now we will start our development server, using the given command in your app terminal and start local development server in your system.

php artisan serve

Step 10. Preview

Using user details, we will get auth token using API, we will send a username and password in the payload, and will have a response token for making API authentication.

image

Using an authentication token we will get authorized user data from the database.

image

Logout user using the token, once logout user token will destroy, and the need to log in again for the authentication otherwise API will return an unauthenticated user response.

image

So, I hope you understand very well, you still need further help you can also follow the youtube video, there is all guideline provided in the description, and the video just follows them. I hope you guys learn how to authenticate passport API in laravel 10, that's it, for now, will meet with new topics soon, Thanks


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :