Implement Passport In Laravel

  Smit Pipaliya   Laravel   8 months ago
Implement Passport In Laravel - TechvBlogs

We learning how to implement full user authentication and a simple form of access control in an API using Laravel and Passport.

Installation Requirements:

Install Laravel and Setup Passport

1. Install Laravel

We require a fresh Laravel application to get using the below command:

composer create-project laravel/laravel auth-passport

2. Install Laravel Passport Package

To install Laravel Passport, run the following command:

composer require laravel/passport

3. Run Migration

To transfer tables for Laravel Passport, run the following command:

php artisan migrate

4. Generate Keys

Create Encryption keys token generate for a secured access token,  run following command:

php artisan passport:install

5. Edit AuthServiceProvider.php File

Open the AuthServiceProvider.php file and add the following line to the boot () method:

public function boot()
{
	$this->registerPolicies();

	Passport::routes();
}

6. Edit config/auth.php file

Set passport as your API driver in config/auth.php file:

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

Congratulation, Laravel Passport installed. Next, I will configure it in the Users model.

7. Update the User Model

Now head to the app folder and add a trait to the User model:

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

I will now create a controller and handle the rest of the rest requests.

8. Create a UserController for the REST API in Laravel

Artisan command to create a new controller, run the following command:

php artisan make:controller UserController

Create a new file named UserController.php within it. Open the newly created controller file:

<?php

namespace App\Http\Controllers;

use App\User; 
use Validator;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Auth; 
use Laravel\Passport\Client as OClient; 

class UserController extends Controller
{
    public $successStatus = 200;
    
    // User Login
    public function login()
    {
        if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
            return $this->getTokenAndRefreshToken(request('email'), request('password'));
        } 
        else { 
            return response()->json(['error'=>'Unauthorised'], 401); 
        } 
    }
    
    // User Register
    public function register(Request $request) { 
        $validator = Validator::make($request->all(), [ 
            'name' => 'required', 
            'email' => 'required|email|unique:users', 
            'password' => 'required|min:8|confirmed'
        ]);

        if ($validator->fails()) { 
            return response()->json(['error'=>$validator->errors()], 422);            
        }

        $password = $request->password;
        $input = $request->all(); 
        $input['password'] = bcrypt($input['password']); 
        $user = User::create($input);
        return $this->getTokenAndRefreshToken($user->email, $password);
    }

    // Generate Bearer Token and Refresh Token
    public function getTokenAndRefreshToken($email, $password) { 
        $oClient = OClient::where('password_client', 1)->first();
        $http = new Client;
        $response = $http->request('POST', env('APP_URL').'/oauth/token', [
            'form_params' => [
                'grant_type' => 'password',
                'client_id' => $oClient->id,
                'client_secret' => $oClient->secret,
                'username' => $email,
                'password' => $password,
                'scope' => '*',
            ],
        ]);

        $result = json_decode((string) $response->getBody(), true);
        return response()->json($result, $this->successStatus);
    }
}

The register method above handled the registration process for users of our application. To handle validation and ensure that all it fills the required fields for registration, we used Laravel’s validation method. This validator will ensure that the name, email, password, and password_confirmation fields are required and return the feedback.

Now open the routes/api.php file and add the following routes to it:

Route::post('/register', '[email protected]');
Route::post('/login', '[email protected]');

9. Tests

Now we can run Laravel, run the following command:

php artisan serve

Register User

Implement Passport In Laravel - Laravel - TechvBlogs

Login User

Implement Passport In Laravel - Laravel - TechvBlogs

If you have any queries or doubts about this topic please feel free to contact us. We will try to reach you.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
Laravel Developer
Advertise Here