Laravel 7.x Passport Tutorial Example

Hello Artisan

In this tutorial we are going to learn about laravel passport. In this tutorial i will show you step by step that how to create api authentication using laravel passport. If you ever used laravel passport  for token authentication? 

In this laravel 7 passport tutorial i will show you login registration and logged in user details. In this laravel passport tutorial i will teach you step by step so that you can learn it and can use it.

If you don't know how to create api authentication using laravel passport, then you are a right place. In this example i will show you how to create very simple api authentication with laravel passport.

You have to just follow few step to get following web services.

  • Login API
  • Register API
  • Details API

Above three api through you can simply get by following few step. It is from scratch so just follow bellow step, at last i attach screen shot of api test.

laravel-6-passport-tutorial

 

Now lets start laravel passport tutorial.

Step 1 : Install Laravel

In first step, we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

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

 

Step 2: Install Passport Package

In this step we have to laravel/passpor package for passport method so one your terminal and fire bellow command:

composer require laravel/passport

 

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

config/app.php

'providers' => [

	....

	Laravel\Passport\PassportServiceProvider::class,

],

 

Step 3: Run Migration Command

Read also : Laravel 6 REST API with Passport Tutorial with Ecommerce Project

After Passport service provider registers, we require to run migration command, after run migration command you will get several new tables in database. So, let's run bellow command:

php artisan migrate

 

Next, we need to install passport using command, Using passport:install command, it will create token keys for security. So let's run bellow command:

php artisan passport:install

 

Step 4: Passport Configuration

In this step, we have to configuration on three place model, serviceprovider and auth config file. So you have to just following change on that file.

app/User.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;
}

 

app/Providers/AuthServiceProvider.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();
        Passport::tokensExpireIn(now()->addDays(15));
        Passport::refreshTokensExpireIn(now()->addDays(30));

    }
}

 

Now configure our auth.php file. Here our default api driber is token. Just replace it with passport.

config/auth.php

return [
    .....
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],
    .....
]

 

Step 5 : Setup API Route

In this step, we will create api routes. Laravel provide api.php file for write web services route. So, let's add new route on that file.

routes/api.php

Route::post('login', 'API\[email protected]');
Route::post('register', 'API\[email protected]');

Route::middleware('auth:api')->group(function(){

  Route::post('details', 'API\[email protected]_user_details_info');
  
});

 

Step 6 :  Create & Setup Controller

In last step we have to create new controller and three api method, So first create new directory "API" on Controllers folder. So let's create UserController and put bellow code:

app/Http/Controllers/API/AuthController.php

namespace App\Http\Controllers\API;

use App\User; 
use Validator;
use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth; 
use Symfony\Component\HttpFoundation\Response;


class AuthController extends Controller 
{
  
  CONST HTTP_OK = Response::HTTP_OK;
  CONST HTTP_CREATED = Response::HTTP_CREATED;
  CONST HTTP_UNAUTHORIZED = Response::HTTP_UNAUTHORIZED;

  public function login(Request $request){ 

    $credentials = [

        'email' => $request->email, 
        'password' => $request->password

    ];

    if( auth()->attempt($credentials) ){ 

      $user = Auth::user(); 
      
      $token['token'] = $this->get_user_token($user,"TestToken");

      $response = self::HTTP_OK;

      return $this->get_http_response( "success", $token, $response );

    } else { 

      $error = "Unauthorized Access";

      $response = self::HTTP_UNAUTHORIZED;

      return $this->get_http_response( "Error", $error, $response );
    } 

  }
    
  public function register(Request $request) 
  { 
    $validator = Validator::make($request->all(), [ 

      'name' => 'required', 
      'email' => 'required|email', 
      'password' => 'required', 
      'password_confirmation' => 'required|same:password', 

    ]);

    if ($validator->fails()) { 

      return response()->json([ 'error'=> $validator->errors() ]);

    }

    $data = $request->all(); 

    $data['password'] = Hash::make($data['password']);

    $user = User::create($data); 

    $success['token'] = $this->get_user_token($user,"TestToken");

    $success['name'] =  $user->name;

    $response =  self::HTTP_CREATED;

    return $this->get_http_response( "success", $success, $response );

  }
    
  public function get_user_details_info() 
  { 

    $user = Auth::user(); 

    $response =  self::HTTP_OK;

    return $user ? $this->get_http_response( "success", $user, $response )
                   : $this->get_http_response( "Unauthenticated user", $user, $response );

  } 

  public function get_http_response( string $status = null, $data = null, $response ){

    return response()->json([

        'status' => $status, 
        'data' => $data,

    ], $response);
  }

  public function get_user_token( $user, string $token_name = null ) {

     return $user->createToken($token_name)->accessToken; 

  }

}

 

Now we are ready to run our laravel passport tutorial example project. so run bellow command.

php artisan serve

 

Now, we can simple test by rest client tools, So i test it and you can see bellow screen shot. 

Before Register Api

laravel-passport-tutorial

 

After Completing Register Api

laravel-6-passport-tutorial

 

Before Login Api

laravel-6-passport-token-tutorial

 

After Login Api

laravel-passport

 

Now, we will test details api, In this api you have to set three header as listed bellow:

'headers' => [
    
    'Content-Type' => 'application/json',
     
    'Accept' => 'application/json',

    'Authorization' => 'Bearer'

]

 

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

Before Getting User Details Api

laravel-api-authentication-token-tutorial

 

After Getting User Details Api

laravel-passport

 

So we successfully completed our laravel 7/6 passport tutorial. I hope it can help you.