Laravel 7/6 REST API With Passport Example Tutorial

Laravel 7/6 REST API With Passport Example Tutorial

In this Laravel 7/6 REST APIs with passport auth example tutorial, you will learn how to create restful login, registration, get user info APIs in laravel with passport authentication.

As well as, how you can install passport auth in your laravel application and how you can configure passport auth with your laravel app. Also, you will learn how you can get useful information using a token with a passport auth.

Laravel 7/6 REST API with Passport Tutorial

Follow the below steps and create RESTful APIs in laravel apps with passport auth:

  • Step 1: Install Fresh Laravel Setup
  • Step2: Configure Database Details
  • Step 3: Install Passport Packages in Laravel
  • Step 4: Run Migration and Install Passport Auth
  • Step 5: Passport Configuration
  • Step 6: Create APIs Route
  • Step 7: Create Controller & Methods
  • Step 8: Now Test Laravel REST API in Postman

Step 1: Install Fresh Laravel Setup

Download Laravel fresh setup using below command, Open the command prompt and type the below command:

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

Step 2: Configure Database Details

After successfully installed fresh laravel application setup, Go to your project .env file and set up database credential and then move next step :

 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 Package In Laravel

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,
],

Before you run migration command, go to the app/providers/AppServiceProvider.php and put the two line of code inside a boot method :

 Use Schema; 
public function boot() {
Schema::defaultStringLength(191);
}

Step 4: Run Migration and Install Passport Auth

We need to do migration using the bellow command. This command creates tables in the database :

php artisan migrate

We need to install laravel to generate passport encryption keys. This command will create the encryption keys needed to generate secure access tokens. like secret key and secret id.

php artisan passport:install

Step 5: Laravel Passport Configuration

Configuration of some files. Next open App/User.php file and put the below code on App/User.php File

<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
use HasApiTokens, Notifiable;
/**
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',
];
}

Next Register passport routes in App/Providers/AuthServiceProvider.php, Go to App/Providers/AuthServiceProvider.php and put this => 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(); 
        Passport::routes(); 
    } 
}

config/auth.php

Next, go to 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',
],
],

Step 6: Create APIs Route

In this step, we will create rest API routes in the laravel app.

Go to api.php inside route folder and create below routes here :

 Route::prefix('v1')->group(function(){
  Route::post('login', 'Api\AuthController@login');
  Route::post('register', 'Api\AuthController@register');
  Route::group(['middleware' => 'auth:api'], function(){
  Route::post('getUser', 'Api\AuthController@getUser');
  });
 });

Step 7: Create Controller & Methods

Now will create a controller name AuthController. Use the below command and create a controller :

 php artisan make:controller Api\AuthController

After that, we will create some methods in AuthController. You can see the login, registration and get user info methods in this controller.

<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use App\User; 
use Illuminate\Support\Facades\Auth; 
use Validator;
class AuthController extends Controller 
{
 public $successStatus = 200;
 
 public function register(Request $request) {    
 $validator = Validator::make($request->all(), 
              [ 
              'name' => 'required',
              'email' => 'required|email',
              'password' => 'required',  
              'c_password' => 'required|same:password', 
             ]);   
 if ($validator->fails()) {          
       return response()->json(['error'=>$validator->errors()], 401);                        }    
 $input = $request->all();  
 $input['password'] = bcrypt($input['password']);
 $user = User::create($input); 
 $success['token'] =  $user->createToken('AppName')->accessToken;
 return response()->json(['success'=>$success], $this->successStatus); 
}
 
  
public function login(){ 
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ 
   $user = Auth::user(); 
   $success['token'] =  $user->createToken('AppName')-> accessToken; 
    return response()->json(['success' => $success], $this-> successStatus); 
  } else{ 
   return response()->json(['error'=>'Unauthorised'], 401); 
   } 
}
 
public function getUser() {
 $user = Auth::user();
 return response()->json(['success' => $user], $this->successStatus); 
 }
} 
 Lets got terminal & run the command :

 php artisan serve

Step 8: Now Test Laravel REST API in Postman

Laravel Register Rest API :
laravel register api
laravel register api
Login API :
laravel passport login api
laravel passport login api

Next Step, we 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 passport – We have successfully installed a laravel passport authentication package and also configuration passport package in laravel application. Using the laravel passport package we have successfully created rest login authentication API, register API and get user info API.

Recommended Laravel Tutorial

  1. Laravel Twitter Login Example Using Socialite Package
  2. Laravel Linkedin Login Tutorial With Live Demo
  3. Login with Facebook In Laravel Example
  4. Laravel Socialite Google Login Example
  5. Github Login in laravel with Example
  6. Laravel Multi Auth( Authentication) Example Tutorial
  7. Laravel Custom Login Registration Example Tutorial

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

AuthorTuts Make

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, Codeigniter, Vue JS, Angular JS, React Js, WordPress and Bootstrap from a starting stage.

One reply to Laravel 7/6 REST API With Passport Example Tutorial

  1. What about refresh token?

Leave a Reply

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