Laravel Passport integration

if you want to develop mobile application so Web Services is very important, you need to create API. As we know laravel is very popular because of creating API but if you are beginner and want to know how to create API and webservices you are in right place. I will show how to create simple API and authentication. we need to know what is passport and how to integrate in laravel.

Laravel passport ?

in Laravel API authentication works like gentle wind using Laravel Passport. API will use tokens to authenticate users and do not maintain session between requests.

Install passport package

composer require laravel/passport

After successfully installed package, open config/app.php file and add under service provider.

config/app.php

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

migrate and install

if you will added service provider registers, we need to run migrate command. when you will run migrate then it will create some more table in database.

php artisan migrate

now, we need to run passport install command. then it will generate token keys things.

php artisan passport:install

Passport setting

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

<?php
namespace App\Providers;
use Laravel\Passport\Passport; //added
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',  //added
    ];
/** 
     * Register any authentication / authorization services. 
     * 
     * @return void 
     */ 
    public function boot() 
    { 
        $this->registerPolicies(); 
        Passport::routes(); //added
    } 
}

config/auth.php

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

create route

now, I will create API route, laravel provides api.php file for create route for webservices.

routes/api.php

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\UserController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| 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::group(['namespace'=>'API'], function(){
	Route::group([
	  //'prefix' => 'auth'
	], function() {
		Route::post('login', [UserController::class, 'login'])->name('login');
		Route::post('register', [UserController::class, 'register'])->name('register');
        Route::post('verify_otp', [UserController::class, 'verify_otp'])->name('verify_otp');
	});
});

Create Controller

now, firstly I need to create new folder API under app\Http\Controllers folder. I will create new controller called UserController.php

UserController.php

<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use App\Models\User;
use Illuminate\Support\Facades\Auth; 
use Validator;
use Illuminate\Support\Facades\Hash;
use Mail; 
use Illuminate\Support\Str;
use DB;
use Carbon\Carbon;
use Spatie\Permission\Models\Role;
class UserController extends Controller 
{
public $successStatus = 200;
/** 
     * login api 
     * 
     * @return \Illuminate\Http\Response 
     */ 
    public function login(Request $request){ 
        $validator = Validator::make($request->all(), [ 
            'email' => 'required|email', 
            'password' => 'required', 
        ]);
        if ($validator->fails()) { 
           return response()->json(['status'=>false,'message'=>$validator->errors()->first()]);       
        }
        $users_id = User::where('email',$request->email)->pluck('is_email_verified')->toArray();
         if(!empty($users_id))
                {
                     $is_email_verified=$users_id?$users_id[0]:[];
                     if($is_email_verified)
                     {   
                        $credentials = $request->only('email', 'password','is_email_verified');
                        if (Auth::attempt($credentials)) {
                            $user = Auth::user(); 
                            $success['status'] = true; 
                            $success['message'] = "Logged in successfully.";
                            $success['user'] =$user;
                            $success['token'] =  $user->createToken('MyApp')->accessToken; 
                            return response()->json($success, $this->successStatus);

                        }else
                            { 
                                return response()->json(['status'=>false,'message'=>'Login authetication failed'], 401); 
                      
                            }
                     }else
                     {
                         return response()->json(['status'=>false,'message'=>'Your account not verify. Please verify account.'], 401); 
                     }

                 }else
                 {
                    return response()->json(['status'=>false,'message'=>'Login authetication failed'], 401); 
                 }
       
    }
/** 
     * Register api 
     * 
     * @return \Illuminate\Http\Response 
     */ 
    public function register(Request $request) 
    { 
        $validator = Validator::make($request->all(), [ 
            'name' => 'required', 
            'email' => 'required|email|unique:users', 
            'password' => 'required|min:8', 
            'c_password' => 'required|same:password', 
        ]);
		if ($validator->fails()) { 
		        return response()->json(['status'=>false,'message'=>$validator->errors()->first()]);             
		        }
		$input = $request->all(); 
        $otp = rand(1000,9999);
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'otp'=>$otp,
        ]);
         if($user){           
              Mail::send('emails.OTPVerificationEmail', ['otp' => $otp], function($message) use($request){
                  $message->to($request->email);
                  $message->subject('OTP Received for account verification');
            });
           
             return response()->json(["status" => true, "message" => "OTP sent successfully"]);
        }
        else{
             return response()->json(["status" => false, 'message' => 'failed']);
        } 
    }
/** 
     * verify_otp api 
     * 
     * @return \Illuminate\Http\Response 
     */ 
    public function verify_otp(Request $request) 
    { 
        $validator = Validator::make($request->all(), [ 
            'email' => 'required|email', 
            'otp' => 'required', 
        ]);
        if ($validator->fails()) { 
           return response()->json(['status'=>false,'message'=>$validator->errors()->first()]);             
        }
        $user  = User::where([['email','=',$request->email],['otp','=',$request->otp]])->first();
        
        $roles=array('User');
        $user->assignRole($roles);
        if($user){
            User::where('email','=',$request->email)->update(['otp' => null,'is_email_verified'=>true]);
            $user_data  = array('id'=>$user->id,'name'=>$user->name,'email'=>$user->email);
            $success['status'] = true;             
            $success['user'] =$user_data;
            $success['message'] = "Your e-mail is verified. You can now login.";
            $message = "Your e-mail is verified. You can now login.";
                 try {
                    $to_address=$user->email;
                    $verification_data=array('email' =>$user->email,
                                             'name' => $user->name);
                    $varifyemail= \Mail::send('emails.registrationEmail', ['verification'=>$verification_data], function($message) use ($to_address) { $message->to($to_address)->subject('Congratulation, on verifying your account'); });
                 
                }
                  catch(Exception $e) {
               }
            return response()->json($success, $this->successStatus);
        }
        else{
             return response()->json(["status" => false, 'message' => 'Invalid OTP']);
        }

    }

API testing
register api

login api

2 thoughts to “Laravel Passport integration”

Leave a Reply

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

− 6 = 1