Laravel 6 | Create API Authentication using Laravel Passport

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.

In this laravel 6 passport tutorial i will show you login registration and logged in user details. So lets start our laravel api authentication token tutorial.

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

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 6 passport tutorial. I hope it can help you.

Codechief is a very fast growing community among programmers and have a reach of around 1 million+ readers globally. Contribution at Codechief is open for all those who have a passion to learn and help others by sharing their knowledge. If you think you have the zeal to learn, start contributing on Codechief contribute. you can also mail your article to [email protected] See your article appearing on the codechief main page and help other code.

We believe that everyone has the right to learn, so we allow both students and professionals to contribute on Codechief.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using JavaScript, Laravel & Wordpress specifically. Facebook Github Website