DEV Community

Arman Hassan
Arman Hassan

Posted on

Laravel 8 Passport OAuth 2.0

Hello* Amigos how's this going? For every application authentication system to controls the potentials of the application. Laravel applications are quite secure through but to handle the authentication part normally we use the basic Scaffolding authenticate system of Laravel. When we need to handle the authenticate system with API's there's some security layer issue that occurs. Because API uses tokens to authenticate between request-ends but it does not maintain session states. In laravel to make the authentication system more secure in cross-application, a better option is using OAuth 2.0.
Let's learn about the OAuth2.0 and implement it via using Laravel package Passport

Table Of Contents

  1. Reasons To Use Passport & OAuth2.0
  2. Overview
  3. OAuth Workflow
  4. Installation
  5. Setup Client
  6. Conclusion

Reasons To Use Passport & OAuth2.0

While setting up the authentication system in our Laravel application the first question will rise that When and why should we need to use the Laravel Passport package and OAuth2.0 server. right? Valid question...
It depends on your Laravel application ground state. If your application needs cross-application authorization support then using OAuth2.0 via Laravel Passport is the best option. However, if an application requires only attempting to authenticate a single-page application, mobile application, or issue API tokens then don't need to use OAuth 2.0.

Overview

Laravel Passport provides a full OAuth2 server implementation for your applications. Is registers own database migration directory and create the tables your application needs to store OAuth2 clients and access tokens so you should migrate your database. With passport using OAuth2.0 provides secure delegated access over HTTP and authorizes Devices, APIs, Servers with access tokens instead of sharing credentials.

OAuth 2.0

OAuth Workflow

Mainly OAuth 2.0 has three main roles

  1. Users (Resource Server)
  2. Applications
  3. API's (Authorize Server)

To get a better understanding of the OAuth workflow lets to assume some examples to think the end-points first. The application sends the request to the resources server to provide the grant code then the resources server sends back the grand code to the application via API's authorized server this is how OAuth workflow works.

Installation

To use the Laravel passport package we need to open the terminal and create a laravel application with the composer command

composer create-project laravel/laravel PassportTest
Enter fullscreen mode Exit fullscreen mode

This command creates a fresh laravel app.

For Basic Authenticate we will use Laravel Breeze to automatically scaffold the application with the routes, controllers, and views you need to register and authenticate.

To install Breeze run this command

composer require laravel/breeze --dev

php artisan breeze: install

npm install && npm run dev
Enter fullscreen mode Exit fullscreen mode

Homepage

Now we need to run the composer command to install passport in the application

composer require laravel/passport
Enter fullscreen mode Exit fullscreen mode

After running this command need to migrate to get the passport package migration files

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

terminal

We have all the required migrations files in our database now need to install passport via this command

php artisan passport:install
Enter fullscreen mode Exit fullscreen mode

passport:install

Now need to modify the User Model file in app/Models/Users.php and add this trait

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}
Enter fullscreen mode Exit fullscreen mode

Now need to add in the app\Providers\AppServiceProvider.php
to call the routes in the boot method

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Laravel\Passport\Passport;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        //
    }

    public function boot()
    {
        Passport::routes();
    }
}
Enter fullscreen mode Exit fullscreen mode

Now let's configure the default guards from the config/auth.php file by setting up the API driver to the passport


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

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],
Enter fullscreen mode Exit fullscreen mode

Installation complete into the app.

Setup Client

In Register, File lets get to register a user

Register Page

Now add client add form in dashboard.blade.php file

<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Dashboard') }}
        </h2>
    </x-slot>

    {{-- <div class="container mx-auto"> --}}
        <div class="flex">
            <div class="w-1/2">
                <div class="p-6">
                    <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                        <div class="p-6 bg-white border-b border-gray-200">
                            <form method="POST" action="/oauth/clients">
                                @csrf

                                <!-- Name  -->
                                <div>
                                    <x-label for="name" :value="__('name')" />
                                    <x-input id="name" class="block mt-1 w-full" type="text" name="name" :value="old('name')"  placeholder="Client name" required autofocus />
                                </div>

                                <!-- url  -->
                                <div class="py-4">
                                    <x-label for="redirect" :value="__('Redirect Link')" />
                                    <x-input id="redirect" class="block mt-1 w-full" type="text" name="redirect" placeholder="https://facebook.com" required autofocus />
                                </div>


                                <div class="flex  justify-start">
                                    <x-button >
                                        {{ __('Create Client') }}
                                    </x-button>
                                </div>

                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <div class="w-1/2">
                {{-- mx-auto sm:px-6 lg:px-8 --}}
                <div class="p-6">
                    <div class=" overflow-hidden shadow-sm sm:rounded-lg">
                        <div class="bg-white p-6 border-b border-gray-200">
                            <h2>Clients</h2>
                            @foreach ($clients as $client)
                            <div class="bg-gradient-to-r from-yellow-100 to-yellow-100 p-2 my-4">
                                <div class="max-w-6 mx-auto">
                                  <h2 class="text tracking-tight text-gray-900 ">
                                    <span class="block"><b>ID: </b>{{ $client->id }}</span>
                                    <span class="block"><b>Name: </b>{{ $client->name }}</span>
                                    <span class="block"><b>Secret: </b>{{ $client->secret }}</span>
                                    <span class="block"><b>Provider: </b>
                                        @if($client->provider == null )
                                            Null
                                        @else
                                            {{ $client->provider }})
                                        @endif
                                    </span>
                                    <span class="block"><b>Redirect: </b>{{ $client->redirect }}</span>
                                    <span class="block"><b>Access: </b>{{ $client->personal_access_client }}</span>
                                    <span class="block"><b>CLient Password: </b>{{ $client->password_client }}</span>
                                    <span class="block"><b>Revoked: </b>{{ $client->revoked }}</span>
                                  </h2>
                                </div>
                              </div>
                            @endforeach
                        </div>
                    </div>
                </div>
            </div>
        </div>
    {{-- </div> --}}

</x-app-layout>

Enter fullscreen mode Exit fullscreen mode

Here we are adding a form for creating a client credential and redirect callbacks then we also show the inputs on one page. After inserting two data the page will look like this. that's a successful workable passport with OAuth.

Image description

Now to test the system we need to go in the POSTMAN for API request checking

The postman needs to add a new request with the GET method and paste the URL in the URL field and all the specified fields like redirect_url, client_id, secret_code, and a 40 random number in the state for a random token type password. the send the request and we can see a login page where we can log in and this request will redirect into a new page authorization page.

Conclusion

Laravel Passport makes it super easy to install and use for API authentication and authorization into another site from our laravel site without registering from the very beginning and sharing the same credentials manually.
Thank you for reading.

Discussion (0)