menu

Laravel API authentication using passport

Introduction

Laravel already makes it easy to perform authentication via traditional login forms, but what about APIs? APIs typically use tokens to authenticate users and do not maintain session state between requests. Laravel makes API authentication a breeze using Laravel Passport, which provides a full OAuth2 server implementation for your Laravel application in a matter of minutes. Passport is built on top of the League OAuth2 server that is maintained by Andy Millington and Simon Hamp.

Getting Started

Step 1: Install Larvel

If you have an existing Laravel running project, then you can skip this step. Otherwise, we require to get fresh Laravel application using below command, So open your terminal or command prompt and run command below:

    
      composer create-project --prefer-dist laravel/laravel project_name
    
Step 2: Install Laravel Passport Package

To get started, install Passport via the Composer package manager:

    
      composer require laravel/passport
      
Step 3: Run Migration

Firstly, setup your database with project through .env file:

    
      DB_DATABASE=laravel
      DB_USERNAME=root
      DB_PASSWORD=
    

Then do the migrations, Passport migrations will create the tables for your application in database that stores clients and access tokens.

   
     php artisan migrate 
 
Step 4: Generate keys

This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create “personal access” and “password grant” clients which will be used to generate access tokens:

   
     php artisan passport:install
   
 
Step 5: Passport Config

Add the Laravel\Passport\HasApiTokens trait to your App\User model. This trait will provide a few helper methods to your model which allow you to inspect the authenticated user’s token and scopes and HasApiTokens in User class:

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

Next, you should call the Passport::routes method within the boot method of your App/Providers/AuthServiceProvider. This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens. And Add this trait also use Laravel\Passport\Passport;

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

Finally, in your config/auth.php configuration file, you should set the driver option of the api authentication guard to passport. This will instruct your application to use Passport’s TokenGuard when authenticating incoming API requests:

  
    'guards' => [
          'web' => [
              'driver' => 'session',
              'provider' => 'users',
          ],
          'api' => [
              'driver' => 'passport',
              'provider' => 'users',
          ],
      ], 
 
NOTE – In these first five steps, Installation of passport on any Laravel project has been done

Passport Authentication

Step 1: Create Route

Open api.php from routes folder , and replace the code of route with the following

  
    Route::group([
      'prefix' => 'auth'
    ], function () {
      Route::post('login', 'AuthController@login');
      Route::post('register', 'AuthController@register');

      Route::group([
        'middleware' => 'auth:api'
      ], function() {
          Route::get('logout', 'AuthController@logout');
          Route::get('user', 'AuthController@user');
      });
    });
        
Step 2: Create Controller

Create new controller in Http/Controllers/AuthController.php by the following command:

  
    php artisan make:controller AuthController
  
        

Create API and test the API, use a tool called Postman, you may have different IP and port number and after the port number, you should use this /api/auth/signup

1: Register API
  
    <?php

    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Auth;
    use Carbon\Carbon;
    use App\User;
    use Validator;
    class AuthController extends Controller
    {
        /**
        * Create user
        *
        * @param  [string] name
        * @param  [string] email
        * @param  [string] password
        * @param  [string] password_confirmation
        * @return [string] message
        */
        public function register(Request $request)
        {
            $request->validate([
                'name' => 'required|string',
                'email' => 'required|string|email|unique:users',
                'password' => 'required|string|',
                'c_password'=>'required|same:password',
            ]);

            $user = new User([
                'name' => $request->name,
                'email' => $request->email,
                'password' => bcrypt($request->password)
            ]);
            if($user->save()){
                return response()->json([
                    'message' => 'Successfully created user!'
                ], 201);
            }else{
                return response()->json(['error'=>'Provide proper details']);
            }
          }
        }
        
1.1: Test Register API
register
2: Login API
  
    /**
    * Login user and create token
    *
    * @param  [string] email
    * @param  [string] password
    * @param  [boolean] remember_me
    * @return [string] access_token
    * @return [string] token_type
    * @return [string] expires_at
    */
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
            'remember_me' => 'boolean'
        ]);
        $credentials = request(['email', 'password']);
        if(!Auth::attempt($credentials))
            return response()->json([
                'message' => 'Unauthorized'
            ], 401);
        $user = $request->user();
        $tokenResult = $user->createToken('Personal Access Token');
        $token = $tokenResult->token;
        if ($request->remember_me)
            $token->expires_at = Carbon::now()->addWeeks(1);
        $token->save();
        return response()->json([
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => Carbon::parse(
                $tokenResult->token->expires_at
            )->toDateTimeString()
        ]);
    }
        
2.1: Test Login API
login
3: Logout API
  
    /**
    * Logout user (Revoke the token)
    *
    * @return [string] message
    */
    public function logout(Request $request)
    {
        $request->user()->token()->revoke();
        return response()->json([
            'message' => 'Successfully logged out'
        ]);
    }
        
3.1: Test Logout API
logout
4: Get Authenticated User API
  
    /**
    * Get the authenticated User
    *
    * @return [json] user object
    */
    public function user(Request $request)
    {
      return response()->json($request->user());
    }
        
4.1: Test Authenticated User API
user
Step 3: Run API

Now we are ready to run our API. Run below command.

  
    php artisan serve
          

You will get an url something like this http://localhost:8000 or http://127.0.0.1:8000

Run Materialize-Laravel-Passport

Step 1: Run the project

Firstly, you need to run the project, so follow the steps under the Getting Started of materialize-laravel

Step 2: Database setup

Now go to your .env file and change the database credentials

  
    DB_DATABASE=laravel
    DB_USERNAME=root
    DB_PASSWORD=
      
Step 3: Migration

Now run the php artisan migrate command and this will generate the required tables of laravel and passport in your database.

  
    php artisan migrate
      
Step 4: passport:install

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

  
    php artisan passport:install
      
;