Cover Image for PHP Laravel 5.6 Rest API with Passport
171 views

PHP Laravel 5.6 Rest API with Passport

To create a RESTful API with Laravel 5.6 and implement authentication using Laravel Passport, follow these steps:

  1. Install Laravel and Set Up Your Project:
    Install Laravel 5.6 using Composer if you haven’t done so already:
   composer create-project --prefer-dist laravel/laravel project-name "5.6.*"
  1. Set Up Database:
    Configure your .env file with the necessary database credentials to connect to your database.
  2. Install Laravel Passport:
    Run the following command to install Laravel Passport:
   composer require laravel/passport
  1. Set Up Passport:
    After installing Passport, run the following command to create the necessary database tables for Passport:
   php artisan migrate

Next, run the passport:install command to create the encryption keys required for token generation:

   php artisan passport:install
  1. Configure Passport in AuthServiceProvider:
    In the AuthServiceProvider class (located at app/Providers/AuthServiceProvider.php), add the following line in the boot() method to enable Passport routes and functionality:
   use Laravel\Passport\Passport;

   public function boot()
   {
       $this->registerPolicies();

       Passport::routes();
   }
  1. Create User Model:
    Create a User model or use the existing one. Make sure the model uses the HasApiTokens trait, which comes with Laravel Passport:
   use Laravel\Passport\HasApiTokens;
   use Illuminate\Foundation\Auth\User as Authenticatable;

   class User extends Authenticatable
   {
       use HasApiTokens;

       // Rest of your user model code
   }
  1. Set Up API Routes:
    In the routes/api.php file, define your API routes and their corresponding controllers. For example:
   Route::group(['middleware' => 'auth:api'], function () {
       // Your protected API routes here
   });
  1. Create AuthController for Login and Register:
    Create an AuthController to handle user registration and login. You can use Laravel’s built-in authentication scaffolding or create custom controller methods.
  2. Protect API Routes:
    Use the auth:api middleware on routes that require authentication. This middleware will validate the access tokens sent with the API requests.
  3. Testing the API:
    Use tools like Postman to test your API endpoints. To obtain an access token, make a POST request to /oauth/token with the client credentials and user credentials. The response will include the access token, which you can use to access the protected routes.

That’s it! Now you have a RESTful API built with Laravel 5.6 and secured with Laravel Passport for authentication using OAuth2. You can now access your API endpoints by sending the appropriate access tokens with your requests.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS