Laravel 8 Passport OAuth 2.0
Tags: webdev, tutorial, php, laravel
Published: 2021-11-22 04:11:43

*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](#rtupa)
>2. [Overview](#overview)
>3. [OAuth Workflow](#or)
>4. [Installation](#installing)
>5. [Setup Client](#scr)
>3. [Conclusion](#Conclusion)


<h3><a name="rtupa" href="#rtupa" class="anchor"></a>
  Reasons To Use Passport & OAuth2.0
</h3>


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`.

<h3><a name="overview" href="#overview" class="anchor"></a>
  Overview
</h3>

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m3qptdahsibr3eahtjwh.png)

<h3><a name="or" href="#or" class="anchor"></a>
  OAuth Workflow
</h3>

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.

<h3><a name="installing" href="#installing" class="anchor"></a>
  Installation
</h3>

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

```php
composer create-project laravel/laravel PassportTest
```
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

```php
composer require laravel/breeze --dev

php artisan breeze: install

npm install && npm run dev
```
![Homepage](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f2ra8q8nytrimufzhpra.png)

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

```php
composer require laravel/passport
```
After running this command need to migrate to get the passport package migration files

```php
php artisan migrate
```

![terminal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wapjz6c7d2rindi4kvvw.png)

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

```php
php artisan passport:install
```
![passport:install](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a27pcrqdch5ufofswako.png)

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

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

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

```php
namespace App\Providers;

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

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

    public function boot()
    {
        Passport::routes();
    }
}
```

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

```php

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

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],
```
Installation complete into the app. 

<h3><a name="client" href="#client" class="anchor"></a>
  Setup Client
</h3>

In Register, File lets get to register a user

![Register Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lxkflzpy9fw9arwb2zda.png)

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

```html
<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>

```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ovbqj0ca79mlz2kxgeog.png)


 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.


<h3><a name="Conclusion" href="#Conclusion" class="anchor"></a>
  Conclusion
</h3>
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.