Laravel 8 REST API With Passport Authentication Example

Laravel

60

w3alert.com

17-11-2020


Laravel 8 rest api with passport auth tutorial. In this example, i will explain you how to create rest api with passport auth in laravel 8 app. And you will learn step by step how to create rest ful apis with passport authencation in laravel 8 app.

Create or build rest APIs in laravel web application with passport auth. Here you will learn how to create or build rest APIs in laravel web applications. And also you will learn how to install a passport auth package and configure this package in your laravel web applications.

This tutorial has the aim to teach to you how to install, configure and passport the auth package and create restful APIs in your laravel 8 applications.

Laravel 8 Create REST Apis with Passport Auth Tutorial Example

  • Install Laravel 8 App
  • Configure Database Detail
  • Run Migration
  • Install Passport Auth & Configure
  • Create Routes
  • Generate Controller By Artisan
  • Start Development Server

Install Laravel 8 App

First Step, you need to download or install laravel web application new setup on your local machine. you can use the following command to download or install laravel application new setup:

composer create-project laravel/laravel laravel-rest-apis –-prefer-dist

If you want to install a specific version of laravel, you can follow the following tutorial

https://w3alert.com/laravel-tutorial/laravel-install-on-windows-ubuntu-with-composer

Configure Database Detail

After that, you will set up the database credentials in .env file. So open your .env file and update database credentials following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=root

Run Migration

Next, go to command prompt and run the following command:

php artisan migrate

OR

php artisan migrate:fresh

This php artisan migrate command creates a table in your database.

Install Passport Auth & Configure

Here, you will use the following command to install passport package in your laravel web applications

composer require laravel/passport

After successfully install a laravel passport, you can register providers. So go to config/app.php update the following codes:

// config/app.php

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

Install Passport Auth

Here you will need to install and generate passport encryption keys. The following command generate secret key and secret id.

php artisan passport:install

Laravel Passport Configuration

Here you need to register passport routes in App/Providers/AuthServiceProvider.php. So Go to App/Providers/AuthServiceProvider.php and update  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(); 
        Passport::routes(); 
    } 
}

Next Open config/auth.php and 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', 
         ], 
     ],

After that, open App/Models/User.php file and update the following line use Laravel\Passport\HasApiTokens;, and use HasApiTokens, Notifiable; into your User.php file. You can following 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\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;

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

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

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];
}

Create Routes

Next step, go to routes/web.php file and update the following routes into your file:

use App\Http\Controllers\API\AuthController;


Route::prefix('v1')->group(function(){

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

Route::post('register', [AuthController::class, 'register']);

 Route::group(['middleware' => 'auth:api'], function(){

   Route::post('fetchUser', [AuthController::class, 'loggedUser']);

 });

});

Generate Controller By Artisan

Now, you need to generate or create a controller file using php artisan command, so use the php artisan make:controller command and generate/create a new controller file:

php artisan make:controller API/AuthController

In this controller, we will make 3 methods. The first method name is registration(), the second method name is login() and the third method name is loggedUser()

After that, go to App/Http/Controllers/API directory and find the created AuthController.php controller file and update the following code into your file:

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

use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use Illuminate\Support\Facades\Auth; 
use Validator;
use App\Models\User; 

class AuthController extends Controller 
{
 public $statusCode = 200;
  
 public function register(Request $request) 
 {  

    request()->validate([
    'name' => 'required',
    'email' => 'required|email',
    'password' => 'required',  
    'c_password' => 'required|same:password', 
    ]);

    $input = $request->all();  

    $input['password'] = bcrypt($input['password']);

    $user = User::create($input); 

    $success['token'] =  $user->createToken('AppName')->accessToken;

    return response()->json(['success'=>$success], $this->statusCode); 
}
  
   
public function login(Request $request)
{ 

    request()->validate([
    'email' => 'required|email',
    'password' => 'required',  
    ]);

    if(Auth::attempt(['email' => $request->email, 'password' => $request->password]))
    { 
       $user = Auth::user(); 
       $success['token'] =  $user->createToken('AppName')->accessToken; 
       return response()->json(['success' => $success], $this->statusCode); 
    } 
    else
    { 
      return response()->json(['error'=>'Unauthorised'], 401); 
    } 
}
  
  
public function loggedUser() 
{
  $user = Auth::user();
  return response()->json(['success' => $user], $this->statusCode); 
}

} 

Start development server

You can use the following command artisan command to start the development server:

php artisan serve

The final step, go to your postman call APIs with required parameters:

http://localhost:8000/login

OR

http://localhost/laravel-rest-apis/public/login