Create REST API using Passport Laravel 5.8 Authentication

In this laravel 5.8 rest authentication api example, we would love to share with you how to create rest full api in laravel 5.8 using passport. Step by Step guide to build rest api in laravel application using passport authentication in laravel applications. Laravel passport authenticate users and do not maintain session.

Today, first of all we will install laravel new setup and second install laravel passport package for creating a rest full api and using the api we will authentication users in laravel based app.

Contents

  • Download Fresh Laravel 5.8 Setup
  • Install Passport Packages in Laravel
  • Run Migration and Install Laravel Passport
  • Passport Configuration
  • Create Api Route
  • Create Controller & Methods
  • Conclusion

Download Fresh Laravel 5.8 Setup

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

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

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

Run Migration and Install Laravel Passport

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

php artisan migrate

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

php artisan passport:install

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

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 ot config/auth.php and Change the api driver to session to passport . Put this code ‘driver’ => ‘passport’, in api :


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

Create API Route

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

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

Create Controller

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

 php artisan make:controller Api\AuthController

After that we will create some methods in authController :

<?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/blog/public/Api/v1/(here route)

Now Test Rest Api in Postman

Laravel Register 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 header followning :

 
Call login or register apis put $accessToken.

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

]

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

Conclusion

Laravel passport – We have successfully install laravel passport package and also configuration passport package in laravel application. Using the laravel passport package we have successfully create rest authentication login api, register api and get user info api.

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

Spread the love

5 Comments

  1. Pedro Augusto Bortolini said:

    Excelente!! Salvou o meu dia de estagiário.

    March 27, 2019
    Reply
  2. mohamed hasan said:

    excellent work , short and straight forward. Thanks a lot.

    April 6, 2019
    Reply
  3. Abdulla said:

    I just wanna say thank you for very informative and easy to follow tutorial. Thanks so much!

    June 5, 2019
    Reply
  4. Dio said:

    Nice! works like a charm!

    July 3, 2019
    Reply
  5. Alex said:

    Thank you! 😀

    July 12, 2019
    Reply

Leave a Reply

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