Laravel 9 REST API with Passport Authentication Tutorial

  • 14-05-2022
  • 3048
  • Laravel 9
  • Haresh Chauhan

Watch Youtube Video (HINDI) :

Hello Dear friends

In this post, we'll make a passport authentication for API, So here we need to install a passport in our project, In this example, we will try to make the best passport authentication.

Here, We need to add composer and passport configuration to our project.

We need to make an example login API and get user details using passport.

In this example, we manage requests using passport authentication.

So let's do this example and make great passport authentication for your projects.

In 1st step, we need to install the passport, So open your terminal and run the below-given command.

Step 1 : Passport Install

Composer Install in your project root directory

composer require laravel/passport

After installing the passport we need to migrate. So let's do it.

php artisan migrate

Here we need one more command for passport installation.

php artisan passport:install

After installing composer and passport there needs to be some configuration in the user model So let's make changes in the model.

Step 2 : Make configuration in the User model

app/models/User.php

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

After changes in model, we'll change in AuthServiceProvider.

Step 3 : Change In AuthServiceProvider

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;
 
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();
 
        Passport::tokensExpireIn(now()->addDays(15));
    }
} 

After above changes in We make change on config/auth.php

Step 4 : Modify auth.php

config/auth.php

In driver key replace to token to passport and remove hash => true.

'guards' => [
    ... 
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

Step 5 : Create Controller

Now we have to create controller So, let's run command in terminal.

php artisan make:controller API\UserController

app/Http/Controllers/API/UserController.php

<?php
namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Validator;
use Auth;

class UserController extends Controller
{
    public function userLogin(Request $request)
    {
        $input = $request->all();
        $vallidation = Validator::make($input,[
            'email' => 'required|email',
            'password' => 'required'
        ]);

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


        if (Auth::attempt(['email' => $input['email'],'password' => $input['password']])) {
            $user  = Auth::user();
            // dd($user);

            $token = $user->createToken('MyApp')->accessToken;

            return response()->json(['token' => $token]);
        }
        
    }

    public function userDetails()
    {
        $user = Auth::guard('api')->user();

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

Make API routes like below example.

Step 6 : Create API Endpoint like below 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 within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});


Route::post('login',[UserController::class,'userLogin']);

Route::get('profile-details',[UserController::class,'userDetails']);

After this we are ready to run our web application. Let's run given below command in your terminal

php artisan serve

Please check into postman like this please check snapshot and get your API response.

Login API

User Details API

Please set Bearer token and get auth response.


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 :