Laravel 11 REST API with Passport Authentication Example Tutorial

Laravel 11 Restful api authentication with passport auth example; Through this tutorial, i am going to show you how to make restful authentication apis using passport auth in Laravel 11.

Laravel 11 RESTful Authentication API using Passport Tutorial

Use the below given steps to make restful authentication (login, logout, registration and user detail) using passport auth in Laravel 11 apps:

  • Step 1 – Installing Laravel 11 App
  • Step 2 – Database Configuration
  • Step 3 – Installing Passport
  • Step 4 – Configure Passport
  • Step 5 – Run Migration
  • Step 6 – Create Routes
  • Step 7 – Creating API Auth Controller
  • Step 8 – Start Development Server
  • Step 9 – Call Apis On PostMan App

Step 1 – Installing Laravel 11 App

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel latest application using the following command:

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

Step 2 – Database Configuration

In step 2, open your downloaded laravel app into any text editor. Then find .env file and configure database detail like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Installing Passport

In step 3, Navigate to your downloaded LaravelPassportAuth directory. And then install Passport Auth Packages in your Laravel 11. Open terminal and run the following command:

cd / LaravelPassportAuth

composer require laravel/passport

Next, generate token keys for strengthening the security and restrain hackers from deteriorating the security of our applications:

php artisan passport:install

Step 4 – Configure Passport

In step 4, configure passport package in laravel app.

So, open app/User.php file and include HasApiTokens trait inside the User model, as mentioned below:

<?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 Notifiable, HasApiTokens;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

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

After that, open app/Providers/AuthServiceProvider.php file and register the registerPolicies() method inside the boot() function, It will evoke the required routes:

<?php
namespace App\Providers;
use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;


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


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

Now, Configure driver for the Passport. So open auth.php, which is located inside config directory and add the following code into it:

<?php
    return [
    ....
    ....
    
        'guards' => [
            'web' => [
                'driver' => 'session',
                'provider' => 'users',
            ],
    
            'api' => [
                'driver' => 'passport',
                'provider' => 'users',
            ],
        ],
    
    ....
    ....
]

Step 5 – Run Migration

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 6 – Create Routes

In step 6, open your api.php file, which is located inside routes directory. Then add the following routes into web.php file:

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 – Creating API Auth Controller

In step 7, create import and export csv file controller by using the following command:

php artisan make:controller API\AuthController

The above command will create AuthController.php file, which is located inside /app/Http/Controllers/API directory. So add the following code into it:

<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use App\Models\User;

class AuthController extends Controller
{
    /**
     * Registration Req
     */
    public function register(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|min:4',
            'email' => 'required|email',
            'password' => 'required|min:8',
        ]);
 
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password)
        ]);
 
        $token = $user->createToken('Laravel9PassportAuth')->accessToken;
 
        return response()->json(['token' => $token], 200);
    }
 
    /**
     * Login Req
     */
    public function login(Request $request)
    {
        $data = [
            'email' => $request->email,
            'password' => $request->password
        ];
 
        if (auth()->attempt($data)) {
            $token = auth()->user()->createToken('Laravel9PassportAuth')->accessToken;
            return response()->json(['token' => $token], 200);
        } else {
            return response()->json(['error' => 'Unauthorised'], 401);
        }
    }

    public function userInfo() 
    {

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

    }
}

Step 8 – Start Development Server

In step 8, open your command prompt again and run the following command to start development server for your Laravel 11 passport auth:

php artisan serve

Step 9 – Call Apis On PostMan App

Now, open postman app and call Laravel 11 rest api with passport auth app.

I have called login and registration apis on post man app, it looks like:

Register API:
You can test the Laravel Passport API for registering the user:

http://localhost:8000/api/register

Login Passport API:
Check out the Laravel Passport Endpoint for logging-in:

http://localhost:8000/api/login

After that, You need to set this access token as a Bearer Token in the Authorization header for calling this api http://localhost:8000/api/get-user.

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

Recommended Laravel Tutorials

Leave a Comment