Laravel 8 REST API Authentication with Passport

Laravel 8 REST API Authentication with Passport

Laravel 8 API authentication with passport example. In this tutorial, we will show you how to build rest APIs with passport authentication in laravel 8.

As well as will show you how to install passport and configure passport in laravel 8 app.

First of all, you need to know the following things about API:

  • What is API?
  • what is the use of APIs in laravel?

What is API?

API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other. Each time you use an app like Facebook, send an instant message or check the weather on your phone, you’re using an API.

What is the use of API in laravel?

APIs typically use tokens to authenticate users and do not maintain session state between requests. Laravel makes API authentication a breeze using Laravel Passport, which provides a full OAuth2 server implementation for your Laravel application development in a matter of minutes.

So, in this tutorial, you will learn step by step how to create rest API with laravel 8 passport authentication. And as well as how to install and cofigure passport auth in laravel 8 app.

Laravel 8 API Authentication with Passport Tutorial

  • Step 1: Download Laravel 8 App
  • Step 2: Database Configuration
  • Step 3: Install Passport Auth
  • Step 4: Passport Configuration
  • Step 5: Run Migration
  • Step 6: Create APIs Route
  • Step 7: Create Passport Auth Controller
  • Step 8: Now Test Laravel REST API in Postman

Step 1: Download Laravel 8 App

First of all, Open command prompt and run the following command to install laravel 8 app:

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

Step 2: Database Configuration

Then, Navigate root directory of your installed laravel restful authentication api with passport tutorial project. And open .env file. Then add the database details as follow:

 DB_CONNECTION=mysql 
 DB_HOST=127.0.0.1 
 DB_PORT=3306 
 DB_DATABASE=here your database name here
 DB_USERNAME=here database username here
 DB_PASSWORD=here database password here

Step 3: Install Passport Auth

In this step, run the below command and install passport package :

composer require laravel/passport

After successfully install laravel passport, register providers. Open config/app.php . and put the bellow code :

  // config/app.php

'providers' =>[
 Laravel\Passport\PassportServiceProvider::class,
 ],

Now, you need to install laravel to generate passport encryption keys. This command will create the encryption keys needed to generate secure access tokens:

php artisan passport:install

Step 4: Passport Configuration

In this step, Navigate to App/Models directory and open User.php file. Then update the following code into 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\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',
    ];
}

Next Register passport routes in App/Providers/AuthServiceProvider.php, Go to App/Providers/AuthServiceProvider.php and update this line => Register Passport::routes(); inside of boot method:

<?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();
    }
}

Next, Navigate to config/auth.php and open auth.php file. Then Change the API driver to the session to passport. Put this code ‘driver’ => ‘passport’, in API :


[
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],

Step 5: Run Migration

In this step, you need to do migration using the bellow command. This command creates tables in the database :

php artisan migrate

Step 6: Create APIs Route

In this step, you need to create rest API routes for laravel restful authentication apis with passport project.

So, navigate to the routes directory and open api.php. Then update the following routes into api.php file:

use App\Http\Controllers\API\PassportAuthController;

Route::post('register', [PassportAuthController::class, 'register']);
Route::post('login', [PassportAuthController::class, 'login']);
 
Route::middleware('auth:api')->group(function () {
    Route::get('get-user', [PassportAuthController::class, 'userInfo']);
});

Step 7: Create Passport Auth Controller

In this step, you need to create a controller name PassportAuthController. Use the below command and create a controller :

 php artisan make:controller Api\PassportAuthController

After that, you need to create some methods in PassportAuthController.php. So navigate to app/http/controllers/API directory and open PassportAuthController.php file. After that, update the following methods into your PassportAuthController.php file:

<?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('Laravel8PassportAuth')->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('Laravel8PassportAuth')->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);

    }
}

Then open command prompt and run the following command to start developement server:

 php artisan serve

Step 8: Now Test Laravel REST API in Postman

Here, you can see that, how to call laravel 8 restful API with passport authentication:

Laravel Register Rest API :

laravel register api
laravel register api

Login API :

laravel passport login api
laravel passport login api

Next Step, you will call getUser API, In this API you have to set two headers follows:

 
Call login or register apis put $accessToken.

‘headers’ => [
‘Accept’ => ‘application/json’,
‘Authorization’ => ‘Bearer ‘.$accessToken,

]

Pass header in login/register rest API. it is necessary to passport authentication in laravel app

Conclusion

Laravel 8 restful APIs with passport auth tutorial, you have learned how to build rest APIs with passport auth in laravel 8 app. And as well as how to call this APIs on postman app.

Recommended Laravel Posts

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Javascript, JQuery, Laravel, Livewire, Codeigniter, Vue JS, Angular JS, React Js, WordPress, and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *