Install Laravel Passport & Create REST API using Passport
Laravel 07-Aug-2020

Install Laravel Passport & Create REST API using Passport

 

In this article , we will discuss how to Install Laravel Passport and create restfull apis using Laravel Passport . Step by Step Guide to Build Laravel Passport Application and Laravel Authentication apis for our applications. Laravel Passport Authenticate users and do not maintain session .

This rest full api example also working with laravel version 5.8, 5.7 & 5.6.

What is Laravel Passport ?

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 Passport application in a matter of minutes.


Contents

  • Install Laravel
  • Install Laravel Passport Packages
  • Run Migration and Install Laravel Passport
  • Passport Configuration
  • Create Api Route
  • Create Controller & Methods
  • Conclusion

1. Install Laravel

Install  Laravel application using command prompt,  Open  command prompt and Type the below command:

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

 

2. Install Laravel Passport Package

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

composer require laravel/passport

Completed installation of laravel  passport package, 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); 

 }

 

3. Run Migration and Install Laravel Passport

We need to do  migration using bellow command: 

php artisan migrate

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

php artisan passport:install

 

4. Laravel Passport Configuration

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

use Laravel\Passport\HasApiTokens;

use HasApiTokens,

App/User.php

<?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',
];
}

App/Providers/AuthServiceProvider.php

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

Change the api driver to session to passport . Put this code ‘driver’ => ‘passport’,  in api

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

 

5. Create API Route

In this step, go to api.php inside route folder. and we will create routes

routes/api.php

<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes Laravel Passport
|--------------------------------------------------------------------------
|
| 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::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');
});

});

 

 6. Create Controller

let’s  open controller and  create api controller and methods inside of controller .these are methods : 

  • Register
  • login
  • getUser

<?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

or 

http://localhost/larapassport/public/Api/v1/(here route)

  Call Register Api In Postman

Laravel Login Authentication

Laravel Register api

  Call Login Api In Postman:

Laravel Login Authentication

Laravel Login Api

Next Step , we will call getUser api, In this api you have to set two header followning

Call login or register apis put $accessToken. 

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

]

Pass header in login / register api. it is neccessary to passport authentication

GetUser API:

Laravel Login Authentication get user screen

Laravel Get User api

7. Conclusion

We have successfully install passport in laravel also created rest full apis and tested it.

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