Laravel Passport API Authentication Tutorial With Example

In this example, I will explain to you how to do Laravel Passport API Authentication Tutorial With Example. Today, API is also known as Web service. Web services very valuable when you are creating web and mobile app developing. You require to create API for your mobile application developer. As we know laravel is more famous because of creating API. But if you are a starter and you don’t know what is api and web services, then you are a right place. In this example, I will show you how to create simple api and authentication.

What is Passport?

APIs typically use tokens to authenticate users and do not maintain session state between requests. Laravel makes API authentication breeze using Laravel Passport, which provides the full OAuth2 server implementation for your Laravel application in the matter of minutes.

Laravel Passport API Authentication Tutorial With Example

We are going to Configure Laravel Project.

#1: Install Laravel Project

Install Laravel 5.6 Project by the typing following command.

composer create-project --prefer-dist laravel/laravel passportapiauthentication

#2: Configure SQL Database

Now we can setup database credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=passportapiauthentication
DB_USERNAME=root
DB_PASSWORD=

#3: Install Package

We need to install passport via the Composer package manager, so open your terminal and type below command:

composer require laravel/passport

The Passport service provider registers its own database migration directory with a framework, so you should migrate your database after registering the provider. The Passport migrations will create tables your application wants to store clients and access tokens.

php artisan migrate

Next, you should run the passport:install command. This command will create the encryption keys required to generate secure access tokens. Also, the command will create “personal access” and “password grant” clients which will be used to generate access tokens:

php artisan passport:install

#4: Passport Configuration

Next, we have to the configuration on three place model, service providers, and auth config file. So you have to just follow change on that file.

In the model, we added HasApiTokens class of Passport,

In the  AuthServiceProvider we added Passport::routes(),

In auth.php, we added api auth configuration.

app/User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use Notifiable,HasApiTokens;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

app/Providers/AuthServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Passport; 

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
        Passport::routes(); 

        //
    }
}

config/auth.php

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

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

#5: Define Route

We register all route in an api.php file.

Route::post('userlogin', 'API\UserController@userLogin');
Route::post('userregister', 'API\UserController@userRegister');
Route::group(['middleware' => 'auth:api'], function()
{
    Route::get('userdetail', 'API\UserController@userDetail');
});

#6: Create one controller

php artisan make:controller API/UserController

It will build the controller file called UserController.php.

//UserController.php

<?php
namespace App\Http\Controllers\API;
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;
/** 
     * login api 
     * 
     * @return \Illuminate\Http\Response 
     */ 
    public function userLogin()
    { 
        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 userRegister(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 userDetail() 
    { 
        $user = Auth::user(); 
        return response()->json(['success' => $user], $this-> successStatus); 
    } 
}

Now we are ready to run example so run below command to quick run:

php artisan serve

Register API:

Laravel Passport API Authentication Example

Login API:

Laravel 5.6 Passport API Authentication Example

User Detail API:

Now, we will test the user detail api, In this api, you have to set two headers as listed below:

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

]

Laravel 5.6 Passport API Authentication TutorialYou can see the database in below screenshot.

Laravel 5 Passport API Authentication Example

At last, our Laravel Passport API Authentication Tutorial With Example is over.

Add a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.