Laravel API authentication using passport

Laravel Passport provides a full OAuth2 server implementation for your Laravel application in a matter of minutes.


Introduction

Laravel Passport 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.


Passport Or Sanctum?

Before getting started, you may wish to determine if your application would be better served by Laravel Passport or Laravel Sanctum. If your application absolutely needs to support OAuth2, then you should use Laravel Passport.

However, if you are attempting to authenticate a single-page application, mobile application, or issue API tokens, you should use Laravel Sanctum. Laravel Sanctum does not support OAuth2; however, it provides a much simpler API authentication development experience.


Installation

  1. To get started, install Passport via the Composer package manager:
  2. composer require laravel/passport -w
  3. Passport's service provider registers its database migration directory, so you should migrate your database after installing the package. The Passport migrations will create the tables your application needs to store OAuth2 clients and access tokens:
  4. php artisan migrate
  5. Next, you should execute the passport:install Artisan 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:
  6. php artisan passport:install
  7. After running the passport:install command, add the Laravel\Passport\HasApiTokens trait to your App\Models\User model. This trait will provide a few helper methods to your model that allow you to inspect the authenticated user's token and scopes. If your model is already using the Laravel\Sanctum\HasApiTokens trait, you may remove that trait:
  8. <?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;
    use Laravel\Passport\HasApiTokens;
    
    class User extends Authenticatable
    {
        use HasApiTokens, HasFactory, Notifiable;
    }
  9. Finally, in your application's 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:
  10. 'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],

Client UUIDs

You may also run the passport:install command with the --uuids option present. This option will instruct Passport that you would like to use UUIDs instead of auto-incrementing integers as the Passport Client model's primary key values. After running the passport:install command with the --uuids option, you will be given additional instructions regarding disabling Passport's default migrations:

php artisan passport:install --uuids

Deploying Passport

When deploying Passport to your application's servers for the first time, you will likely need to run the passport:keys command. This command generates the encryption keys Passport to generate access tokens. The generated keys are not typically kept in source control:

php artisan passport:keys

If necessary, you may define the path where Passport's keys should be loaded from. You may use the Passport::loadKeysFrom method to accomplish this. Typically, this method should be called from the boot method of your application's App\Providers\AuthServiceProvider class:

/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
    $this->registerPolicies();

    Passport::routes();

    Passport::loadKeysFrom(__DIR__.'/../secrets/oauth');
}

Passport Authentication

We'll create simple user authentication methods via Laravel passport below.

  1. Create Route: Create routes into routes/api.php that point to AuthController:
  2. <?php
    
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\AuthController;
    
    /*
    |--------------------------------------------------------------------------
    | API Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register API routes for your application. These
    | routes are loaded by the RouteServiceProvider within a group which
    | is assigned the "api" middleware group. Enjoy building your API!
    |
    */
    
    Route::group([
      'prefix' => 'auth'
    ], function () {
      Route::post('login', [AuthController::class, 'login']);
      Route::post('register', [AuthController::class, 'register']);
    
      Route::group([
        'middleware' => 'auth:api'
      ], function () {
        Route::get('logout', [AuthController::class, 'logout']);
        Route::get('user', [AuthController::class, 'user']);
      });
    });
  3. Create Controller: Now, we have to create a controller that handles all API requests. Follow below artisan command to create a new controller:
  4. php artisan make:controller AuthController
  5. Register User: We'll implement a simple method to register a user:
  6. <?php
    
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Auth;
    use Carbon\Carbon;
    use App\Models\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']);
          }
        }
      }

    TEST register user API using postman

    register
  7. Login User: In the same file AuthController.php, create a simple login method that generates API token via passport:
  8. /**
    * 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()
      ]);
    }

    TEST Login user API using postman

    login
  9. Get User: In the same file AuthController.php, create a simple method to get the user's details:
  10. /**
    * Get the authenticated User
    *
    * @return [json] user object
    */
    public function user(Request $request)
    {
      $user = Auth::user();
      return response()->json($user);
    }

    TEST get user API using postman

    user
  11. Logout User: In the same file AuthController.php, create a simple method to revoke the token from the user:
  12. /**
    * Logout user (Revoke the token)
    *
    * @return [string] message
    */
    public function logout(Request $request)
    {
      $request->user()->token()->revoke();
      return response()->json([
        'message' => 'Successfully logged out'
      ]);
    }

    TEST logout user API using postman

    logout
© 2017- Pixinvent, Hand-crafted & Made with ❤️