API Authentication using Laravel Passport – Complete Guide 2020

July 11, 2020

In this tutorial we will see how to create API Authentication using Laravel Passport package. This very use full when you write Vue.js application because you have to authenticate your Restful Api using the Laravel Passport Authentication system

Laravel Passport is complete OAuth2 server implementation. If you try to implement OAuth2 from scratch it is complex and time consuming work. Thank to Laravel, you have Laravel Passport which is easy to learn and easy to implement

What is Passport?

Laravel Passport is full OAth2 server implementation. So you find very easy to develop  API based application in Laravel, by using the Passport authentication method

Why do you need Laravel Passport?

You can separate front-end and back-end
You need to get data without session
You can secure your API

You can simply follow the steps given below to implement the Passport

1 Create new Laravel project
2 Install Passport and Configure
3 Create User Interface for managing OAuth clients and tokens
4 Testing OAuth with consumer application

1 Create new Laravel project

Download the Laravel via composer

composer.phar global require "laravel/installer"

Create new Laravel project named oauth

php composer.phar create-project --prefer-dist laravel/laravel oauth

Generate the Authentication scaffolding

php artisan make:Auth

For Laravel >=6

composer require laravel/ui
php artisan ui vue --auth
php artisan migrate

2 Install Passport via the Composer package manager

You can install the Laravel Password package using following command

composer require laravel/passport

Now register the Passport service provider in the providers array of the config\app.php file

Laravel\Passport\PassportServiceProvider::class,

Now you can run the migration command to create tables in the database

php artisan migrate

Now you can create the encryption keys needed to generate secure access tokens

php artisan passport:install

Add the Laravel\Passport\HasApiTokens trait to your App\User model

Next step is to register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens
Add the following code to boot method of the App\Providers\AuthServiceProvider

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

        Passport::routes();
    }

Finally you can update the api of the guard in config\auth.php

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

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

3 Create User Interface for managing OAuth clients and tokens

Now I am going to create interface in OAuth server to manage client applications

 $ php artisan vendor:publish --tag=passport-components
Copied Directory [/vendor/laravel/passport/resources/assets/js/components] To [/resources/assets/js/components/passport]
Publishing complete.

Copy the following code to resources/assets/js/app.js

 Vue.component(
        'passport-authorized-clients',
        require('./components/passport/AuthorizedClients.vue')
    );

    Vue.component(
        'passport-clients',
        require('./components/passport/Clients.vue')
    );

    Vue.component(
        'passport-personal-access-tokens',
        require('./components/passport/PersonalAccessTokens.vue')
    );

Now you can use NPM to rebuild the assets using Webpack

  npm install
  npm run dev

When you complete the rebuilding you can create a page to see OAuth clients and Personal Access Tokens
Run the following code in terminal

php artisan make:controller SettingsController

This will create the SettingsController.php file in App\Http\Controllers namespace. You can add the following code to controller

class SettingsController extends Controller
{
    public function __construct()
        {
            $this->middleware('auth');
        }

        public function index()
        {
            return view('settings');
        }
}

Now you can create the resources\views\settings.blade.php file and add the following code

@extends('layouts.app')

    @section('content')
    @endsection

This is VUE components you added in earlier steps and this will generate all HTML code needed to display client details

Finally, you can add the following code to /routes/web.php file

Route::get('/settings', 'SettingsController@index')->name('settings');

Now you can start the server

php artisan serve

When open the http://127.0.0.1:8000/settings you can see the following screen

4 Testing OAuth with consumer application

In this section we are going to create another Laravel project and do the testing with OAuth server

Crete new Laravel project

laravel new oauth-client

Next I am going to install the Guzzle

composer install guzzlehttp/guzzle

Now you can start the server on port 8001

  php artisan serve --port=8001

Now I am going to make routes to test the application

Route::get('/', function () {
        $query = http_build_query([
            'client_id' => 3, // Replace with Client ID
            'redirect_uri' => 'http://127.0.0.1:8001/callback',
            'response_type' => 'code',
            'scope' => ''
        ]);

        return redirect('http://127.0.0.1:8000/oauth/authorize?'.$query);
});

So this the route entry we need to send authorization request to the OAuth server

Next you can add the following route code to same web.php file and this is the callback handler. This route will receive the code from the OAuth server. It again sends back the request to OAuth server with other parameters like client_id,client_secret etc. After sending the request it will receive the token and it will save in the session

Route::get('/callback', function (Request $request) {
        $response = (new GuzzleHttp\Client)->post('http://127.0.0.1:8000/oauth/token', [
            'form_params' => [
                'grant_type' => 'authorization_code',
                'client_id' => 3, // Replace with Client ID
                'client_secret' => '19PVO5g3ShcbPzmuDGvmJDGCZ2riR5gCdmfion56', // Replace with client secret
                'redirect_uri' => 'http://127.0.0.1:8001/callback',
                'code' => $request->code,
            ]
        ]);

        session()->put('token', json_decode((string) $response->getBody(), true));

        return redirect('/posts');
});

When above route receives the token and save it the session, it will redirect to the following route and display the posts in json format

Route::get('/posts', function () {
        $response = (new GuzzleHttp\Client)->get('http://127.0.0.1:8000/api/posts', [
            'headers' => [
                'Authorization' => 'Bearer '.session()->get('token.access_token')
            ]
        ]);

        return json_decode((string) $response->getBody(), true);
});

Conclusion

If you have done programming with OAuth server before you know how pain full work it is. I know that you do not like it at all.
But thanks to Laravel, you have enjoyable Passport package with lot of features.