Laravel passport authentication (Rest API).


  1. Install Laravel
  2. Install Basic Authentication
  3. Install  Laravel Passport
  4. Create Login API
  5. Create API to get  logged user detail

Prerequisite:


  •  Composer Installation (Download composer from :https://getcomposer.org/ and install composer)
  • Laravel Installation(>=5.5)

  1. Install Laravel

      Create Laravel project using composer :

        composer create-project --prefer-dist laravel/laravel  <projectName>


    2. Install Basic Authentication

Install Laravel scaffolding authentication: It is ready made package for user authentication.It creates authentication routes , controllers and views to get register and login.It also create migration for user and password reset.

      Create authentication via :  php artisan make:auth

Next step is to setup database credential in .env file and run migration using :
                                   php artisan migrate

 3. Install  Laravel Passport


Installation via : composer require laravel/passport

 Laravel passport service uses tables to store access token and client information.To install migration run : php artisan migrate.Following tables should be created:



Run passport:install command.This command will create encryption keys that is needed to generate secure access token and it also create "personal access" and "passport grant" clients which will be used to generate access token.

         php artisan passport:install

After running above command open your User model and add Laravel\Passport\HasApiToken.

<?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;
}

Now, you need to call passport routes by adding Passport::routes in boot method of AuthServiceProvide.

<?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
{
    /**
     * 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();
    }
}
Enable guard for API authentication in config/auth.php..Change API authentication guard  to passport.
'guards' => [
    'web' =>
        'driver' => 'session',
        'provider' => 'users',
    ],

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

Token Lifetimes

By default , token life time will be one year.You can change token lifetime as per your requirement by setting token/refresh token expire time in method boot of AuthServiceProvide.
/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Passport::routes();

    Passport::tokensExpireIn(now()->addDays(15));

    Passport::refreshTokensExpireIn(now()->addDays(30));
}
Now, its time to test passport authentication:

4. Create Login API


1)  You need to create a route for login in routes/api.php:

Route::POST('/user/login','apiController@userLogin')
->name('userLogin');

Controller Name : apiController 
Method : userLogin

'userLogin' ==> Name of the route


2)  create apiController using following  artisan command:


php artisan make:controller apiController




3) Add below method in apiController.php :

 
public function userLogin(Request $request){
    $credentials = $request->only('email', 'password');
    if (Auth::attempt($credentials)) {
//fetch client detail        
 $clientDetail = \Laravel\Passport\Client:: 
where('password_client',1)->first();


        $request->request->add([
         "grant_type" => "password",            
         "username" => $request->email,            
         "password" => $request->password,            
         "client_id"     => $clientDetail->id,    
         "client_secret" => $clientDetail->secret
        ]);
        $tokenRequest = $request->create(
             env('APP_URL').'/oauth/token',
             'post'        );
        $instance = Route::dispatch($tokenRequest);
        return response($instance->getContent(), 200)
         ->header('Content-Type', 'text/plain');

    } }
Now its time test login API.You test it by using postman:
Set Header : Key: Content-Type . Value : application/json.

If all thing is set correctly, you will get response as above.
Now you can use access_token value to call authenticated routes.

5. Create API to get  logged user detail

Let's fetch user information using above access_token: Add route for user detail in routes/api.php:
Route::middleware('auth:api')->get('/user', 
function (Request $request) {    
return $request->user();
});

Call this api using postman:

Add   Key : Autherization and value : 
Bearer <access_token>(generated by login api).





Comments