Create REST API Authentication Using Laravel Passport

Hello Artisan,

This laravel rest api authentication tutorial, I will show you step by step that how we can create a rest api authentication system in laravel using laravel passport. There are many options to create rest api authentication in laravel. But in this example, we are going to use laravel passport package to create rest api authentication.

If you don't know how to create api rest with laravel 7 passport authentication then this example is for you. I will guide you step by step to complete laravel passport rest api authentication system. 

I will create login, register and logout system with  laravel passport. So let's see the example of rest api authentication with laravel passport.

 

laravel-6-passport-tutorial

 

Now let's start laravel passport tutorial.

 

Step 1 : Install Laravel

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

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

 

Step 2: Install Passport Package

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

composer require laravel/passport

 

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

config/app.php

'providers' => [

	....

	Laravel\Passport\PassportServiceProvider::class,

],

 

Step 3: Run Migration Command

 

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

 

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

php artisan migrate

 

Next, we need to install the passport using the command, Using the "passport:install" command, 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 configure on three place model, service provider, and auth config file. So you have to just follow the 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 provides an api.php file for writing web services routes. So, let's add a new route to that file.

routes/api.php

Route::post('login', 'API\AuthController@login');
Route::post('register', 'API\AuthController@register');

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

  Route::post('details', 'API\AuthController@get_user_details_info');
  
});

 

Step 6 :  Create & Setup Controller

In the last step we have to create a new controller and three API methods, So first create a new directory "API" in the 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 simply test by rest client tools, So I test it and you can see the below screenshot. 

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 the details API, In this API you have to set three headers as listed below:

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

    'Authorization' => 'Bearer'

]

 

So, make sure the above header is, 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.

 

#laravel