API authentification with Laravel (5.8) Passport
Tags: tutorial, laravel, php, webdev
Published: 2019-06-13 17:14:51

---
title: API authentification with Laravel (5.8) Passport 
published: true
description: A simple code snippet to authenticate laravel apis with passport.
tags: tutorial,laravel,php,webdev
series: Laravel Journey
cover_image: https://www.cloudways.com/blog/wp-content/uploads/Laravel-Login-Authentication-Banner.jpg
---

Hey copy-pasters,

Yup! it has been a long since i took a lesson for Gatsby. I gotta do something about it to go back on track. 

![lazy](https://media.giphy.com/media/qd7Wlk9nx8VwI/giphy.gif)

But wait, I got something for <code>future me</code> to read or <code>you</code> to read,

Have you ever wondered how to secure laravel apis? Why would you. right? You dont have to . But I do. At work . Thats why i have been using "tymondesigns/jwt-auth" package.

So today i thought i could use 'passport' instead of jwt. I found that passport uses jwt. Passport is a package that implements Oauth2 and jwt. 




Oh Almost forgot. <code>Motivation</code> time .Skip ahead if you dont prefer to be motivated.

<blockquote>If you are having a bad day think about  breakfast you had today. (Unless you are having a bad day just because you dont have breakfast. Irony though) . You have breakfast,So you dont starve even on the start of the day. There are people those who go to work without having breakfast. Not just because they dont have time, but because they can not afford. So be lucky you had food today.</blockquote>

#Main content from Here

<h2>Table of contents</h2>
<ul>
<li>Description</li>
<li>Install Laravel 5.8 via composer</li>
<li>Configure the connection to the database</li>
<li>Install Package</li>
<li>Run Migration</li>
<li>Install Passport</li>
<li>Passport Configuration</li>
<li>Create API Route</li>
</ul>

<center><h1><u>Description</u></h1></center>

## What is [Laravel Passport](https://laravel.com/docs/5.8/passport)? (Just google)
APIs typically use tokens to authenticate users and do not maintain session state between requests. Laravel makes API authentication a breeze using Laravel Passport, which provides a full OAuth2 server implementation for your Laravel application development in a matter of minutes.

Let’s start!

<center><h1><u>Install Laravel 5.8 via composer:
</u></h1></center>


```cmd
composer create-project --prefer-dist laravel/laravel api-authentification</code>
```

<center><h1><u>Configure the connection to the database in our .env file:</u></h1></center>

```env

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=api-authentification
DB_USERNAME=root
DB_PASSWORD=
```

<center><h1><u>Install Package</u></h1></center>

```cmd
composer require laravel/passport
```

After successfully install package, open <code>config/app.php</code> file and add service provider.

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


<center><h1><u> Run Migration and Install</u></h1></center>

After Passport service provider registers, we require to run the migration command, when you run the migration command table will be set in database (You allredy know what migration is. right? right?)

```cmd
php artisan migrate
```

Next install passport, it will create token keys for security. So let’s run below command:

<center><h1><u>Install Passport</u></h1></center>

```cmd
php artisan passport:install
```

<center><h1><u> Passport Configuration</u></h1></center>

In this step, we have to do the configuration on three files

<ul> 
<li>model</li> 
<li>service provider</li>  
<li>auth config file</li>
</ul>

So you have to just follow change on that file.

In model, we are gonna add <code>HasApiTokens</code> class of Passport,

In <code>AuthServiceProvider</code> we are gonna add <code>Passport::routes()</code>,

In <code>auth.php</code>, we added API auth configuration.

app/User.php

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

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

protected $hidden = [
'password', 'remember_token',
];
}
```
<center>app/Providers/AuthServiceProvider.php</center>

```php
<?php
namespace App\Providers;
use Laravel\Passport\Passport; 
use Illuminate\Support\Facades\Gate; 
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider 
{ 
    
    protected $policies = [ 
        'App\Model' => 'App\Policies\ModelPolicy', 
    ];

    public function boot() 
    { 
        $this->registerPolicies(); 
        Passport::routes(); 
    } 
}
```

config/auth.php

```php

<?php
return [
'guards' => [ 
        'web' => [ 
            'driver' => 'session', 
            'provider' => 'users', 
        ], 
        'api' => [ 
            'driver' => 'passport', 
            'provider' => 'users', 
        ], 
    ],
```
 
<center><h1><u> Create API Route</u></h1></center>

Let us add some routes on the api.php file

<center>routes/api.php</center>

```php

<?php

Route::post('login', 'UserController@login');
Route::post('register', 'UserController@register');
Route::group(['middleware' => 'auth:api'], function()
{
   Route::post('details', 'UserController@details');
});


```

<center><h1><u>  Create the Controller</u></h1></center>

In the last step we have to create a new controller and three API methods, 

```php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use App\User; 
use Illuminate\Support\Facades\Auth; 
use Validator;
class UserController extends Controller 
{
public $successStatus = 200;

    public function login(){ 
        if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ 
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')-> accessToken; 
            return response()->json(['success' => $success], $this-> successStatus); 
        } 
        else{ 
            return response()->json(['error'=>'Unauthorised'], 401); 
        } 
    }
 
    public function register(Request $request) 
    { 
        $validator = Validator::make($request->all(), [ 
            'name' => 'required', 
            'email' => 'required|email', 
            'password' => 'required', 
            'c_password' => 'required|same:password', 
        ]);
if ($validator->fails()) { 
            return response()->json(['error'=>$validator->errors()], 401);            
        }
$input = $request->all(); 
        $input['password'] = bcrypt($input['password']); 
        $user = User::create($input); 
        $success['token'] =  $user->createToken('MyApp')-> accessToken; 
        $success['name'] =  $user->name;
return response()->json(['success'=>$success], $this-> successStatus); 
    }

    public function details() 
    { 
        $user = Auth::user(); 
        return response()->json(['success' => $user], $this-> successStatus); 
    } 
}
```
<center>Register response</center>
![register](http://basic.poornathaevents.com/laravel_api/public/images/register.PNG)

<center>Login Response</center>
![login](http://basic.poornathaevents.com/laravel_api/public/images/login.PNG)

Now, we will test details API, In this api, you have to set two headers as listed below:

‘headers’ => [
‘Accept’ => ‘application/json’,
‘Authorization’ => ‘Bearer ‘.$accessToken,

]

So, make sure above header, otherwise, you can not get user details.

<center>Fetch Data</center>
![details](http://basic.poornathaevents.com/laravel_api/public/images/detailsapi.PNG)

Thats it i guess. 

![wohoo](https://media.giphy.com/media/nuQ79LwWfmXeM/giphy.gif)


Its a long post . So probably you may find bugs here. At somepoint If you find yourself  anything kindly keep it yourself.