REST API Authentication With Laravel Passport - Webappfix

  • 27-07-2022
  • 1521
  • Laravel 9
  • Haresh Chauhan

Laravel passport token authentication in API with best tutorial example. passport authenticate client-side application authorize using access token help login auth guard attempt.

Laravel 9 passport token authentication example or API authentication with laravel passport; In this post, You will learn how to install a laravel passport for the API authentication from the client side and how to access authorize API using access token with the help of laravel passport API token.

In this tutorial, We will build an API authentication that will interface to our database and process user data. Using a passport this API will be very secure. This will provide an access token to collect certain protocol data from the server side to the client side.

And with the REST APIs, it will become responsible for the client-side application to store their information and provides all the information server by every request made This constant state transform.

Why is API authentication Important?

The API provides access to collect information from the client side and stored in your database mostly like sensitivity information that you are collecting from the public and where the general public accessing. So that time you must need to know that the user who entered the information is access and permission to stored data.

So let's start integrating Passport in laravel 9.

Step 1: Create Project

Create laravel 9 projects using the given suggested below command in your terminal. This will take a little time to create a laravel project in your system. This command default will take the current version of the laravel.

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

cd passport-auth

Step 2: Database Setup

After Successfully creating the laravel project we will config our database. First, I will go to my PHPMyAdmin and create a database.

Then we will put this database name in the .env the file you will find in your root file. If not found the .env file in your root just create and copy form .env.example file and config.

.env
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=#database_name
DB_USERNAME=#database_username
DB_PASSWORD=#database__password

Step 3: Install Passport

Laravel-9 Multi Authentication Guard Passport API Example

Copy below give the command and paste it into your project root directory terminal. This command will install composer for passport authentication tool in our project.

composer require laravel/passport

Goto you app.php file available in the config folder. add given line in your provider's array property.

config/app.php
'providers' => [
    Laravel\Passport\PassportServiceProvider::class,
],

Migrate your database, Use the below command and migrate all files. This will create all tables in your database and extra another table for passport management also will create.

php artisan migrate

Use the below command in your terminal. This command will install a secret key in our application. This command must need to run else the passport does not work.

php artisan passport:install

Step 4: User Model

Import use Laravel\Passport\HasApiTokens; in your User model. there already will have used Laravel\Sanctum\HasApiTokens; just commit or remove it and use HasApiTokens it inside the User class.

App\Models\User.php
<?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\Sanctum\HasApiTokens; // REMOVE OR COMMENT THIS
use Laravel\Passport\HasApiTokens; // ADD THIS


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

    /**
        * 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',
    ];

    /**
        * The attributes that should be cast.
        *
        * @var array
        */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Step 5: Register In Service Provider

Go in your AuthServiceProvder in your application. import passport use Laravel\Passport\Passport;. Then inside the boot method register Passport::routes().

app/Providers/AuthServiceProvider.php
<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport; // ADD THIS


class AuthServiceProvider extends ServiceProvider
{
    /**
        * The policy mappings for the application.
        *
        * @var array
        */
    protected $policies = [
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
        * Register any authentication / authorization services.
        *
        * @return void
        */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes(); //ADD THIS
    }
}    

Step 6: Guard Setting

In your auth.php file set guard API. just register API attribute inside the guards property. set driver as a passport. set provider users and hash will default false.

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"
    |
    */

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

        'api' => [
            'driver' => 'passport', // ADD THIS PASSPORT DRIVER
            'provider' => 'users',
            'hash' => false,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | 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\Models\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 each reset token will 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 7: Create Login Controller

Create a controller using the below command. This command will create UserLoginController. This is for the register and login and logout method register for the routes.

php artisan make:controller UserLoginController

Add register routes post method for user registration. Add login route from user login and get access token from there. Add prefix authentication group using api:auth middleware.. This route can access only when you have an access token.

Also, Add logout routes from the revoked access token.

routes/api.php
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserLoginController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::post('user/register', [UserLoginController::class, 'user.register']);
Route::post('user/login', [UserLoginController::class, 'user.login']);

Route::middleware('auth:api')->group(function () {
    Route::post('/logout', [UserLoginController::class, 'logout']);
    Route::get('get-user', [UserLoginController::class, 'userDetail']);
});

Step 8: User Controller

All that routes method for user registration with validation. The second method for user login will get an access token for access auth API. The logout method is also available and the get user details method too defined as in routes.

App/Http/Controllers/UserLoginController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

use Validator;
use Hash;
use Auth;

class UserLoginController extends Controller
{
    public function userRegister(Request $request)
    {
        $request = $request->all();

        $validator = Validator::make($request,[
            'name' => 'required|max:55',
            'email' => 'email|required|unique:users',
            'password' => 'required'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors()
            ], 422);
        }

        $request['password'] = Hash::make($request['password']);

        User::create($request);

        return response()->json(['status' => true, 'message' => 'User successfully register.' ], 200);
    }

    public function userLogin(Request $request)
    {
        $request = $request->all();

        $validator = Validator::make($request,[
            'email' => 'email|required',
            'password' => 'required'
        ]);

        if ($validator->fails()) {

            return response()->json([
                'errors' => $validator->errors()
            ], 422);
        }

        if(! Auth::attempt($request)){

            return response()->json(['error' => 'UnAuthorised Access'], 401);
        }

        $accessToken = auth()->user()->createToken('authToken')->accessToken;

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

    public function userDetail(Request $request)
    {
        $user = $request->user();

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

    public function logout (Request $request)
    {
        $token = $request->user()->token();

        $token->revoke();

        $response = ['message' => 'You have been successfully logged out!'];

        return response()->json($response, 200);
    }
}

Step 9: Start Development Server

Start your application development server using below command. Enter below suggested command in your terminal.

php artisan serve

Run & Testing

Before firing any of the APIs we must need a set header for the post request. Accept:application/json

image

Using register API we will register a user. We will enter some user-required details in the x-form body.

image

After registering, We will fire login API with the body user email address which we registered and the user password. The API will return Access Token with the authorise user details.

image

To get the user we need to pass that returned access token to receive user data from the authentication API.

image

And the last logout user using API, Just pass the access token with the logout API in the post method. This token will revoke by the serve side and this token can not access authentication details again until not the user login.

image

CONCLUSION

Cover all 9 steps of this article and you will get passport API authentication API and access token user from this post. I have given the example for a better understanding. each step of this post is important.


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 :