DEV Community

Cover image for API authentification with Laravel (5.8) Passport
Sandeep Balachandran
Sandeep Balachandran

Posted on • Edited on

API authentification with Laravel (5.8) Passport

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

But wait, I got something for future me to read or you 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. Motivation time .Skip ahead if you dont prefer to be motivated.

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.

Main content from Here

Table of contents

  • Description
  • Install Laravel 5.8 via composer
  • Configure the connection to the database
  • Install Package
  • Run Migration
  • Install Passport
  • Passport Configuration
  • Create API Route

Description

What is Laravel 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!

Install Laravel 5.8 via composer:

composer create-project --prefer-dist laravel/laravel api-authentification</code>
Enter fullscreen mode Exit fullscreen mode

Configure the connection to the database in our .env file:


DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=api-authentification
DB_USERNAME=root
DB_PASSWORD=
Enter fullscreen mode Exit fullscreen mode

Install Package

composer require laravel/passport
Enter fullscreen mode Exit fullscreen mode

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

'providers' =>[
Laravel\Passport\PassportServiceProvider::class,
],
Enter fullscreen mode Exit fullscreen mode

Run Migration and Install

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?)

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

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

Install Passport

php artisan passport:install
Enter fullscreen mode Exit fullscreen mode

Passport Configuration

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

  • model
  • service provider
  • auth config file

So you have to just follow change on that file.

In model, we are gonna add HasApiTokens class of Passport,

In AuthServiceProvider we are gonna add Passport::routes(),

In auth.php, we added API auth configuration.

app/User.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',
];
}
Enter fullscreen mode Exit fullscreen mode
app/Providers/AuthServiceProvider.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(); 
    } 
}
Enter fullscreen mode Exit fullscreen mode

config/auth.php


<?php
return [
'guards' => [ 
        'web' => [ 
            'driver' => 'session', 
            'provider' => 'users', 
        ], 
        'api' => [ 
            'driver' => 'passport', 
            'provider' => 'users', 
        ], 
    ],
Enter fullscreen mode Exit fullscreen mode

Create API Route

Let us add some routes on the api.php file

routes/api.php

<?php

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


Enter fullscreen mode Exit fullscreen mode

Create the Controller

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

<?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); 
    } 
}
Enter fullscreen mode Exit fullscreen mode
Register response

register

Login Response

login

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.

Fetch Data

details

Thats it i guess.

wohoo

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

Top comments (2)

Collapse
 
haritsinh profile image
Haritsinh Gohil

Nice tutorial, But It's Better to use Password Grant for first party apps, because personal access token used for testing and Third party apps.

Collapse
 
sandeepbalachandran profile image
Sandeep Balachandran

Excellent. Care to explain more about it?