Build RestFul API Laravel Authenticator (Demo)

Tram Ho

The Authenticator API is still often used to register or login to our system or service. When the user creates an account with the username and password on the server, it will insert that information into the database and then return an access_token.

The purpose of generating this client access_token client to authenticate this device is already registered on our system to prevent uninvited guests coming, you also know that constant call to the server will cause system congestion. serious experience.

Now we will build a few basic APIs as follows using the API Authenticator, here I will use a very useful framework to implement this: Laravel Passport.

Request:

  1. Installed Composer ( Installation guide )
  2. Installed Laravel

Do not worry if you have not installed Laravel, I will guide you right below.

1. Install Laravel

Quite simply, run the following command:

composer global require laravel/installer

After successful installation, type command laravel –version if the following result is successful!

SUCCESS: Laravel Installer 3.1.0

Failed: laravel: command not found

Solution :

You need to install the necessary PHP extensions so Laravel can successfully install. Then run the above command again: composer global require laravel/installer

The laravel extension requires:

PHP> = 7.1.3

BCMath PHP Extension

Ctype PHP Extension

JSON PHP Extension

Mbstring PHP Extension

OpenSSL PHP Extension

PDO PHP Extension

Tokenizer PHP Extension

XML PHP Extension

2. Create project and install Passport

After completing step 1 you can create your own demo project.

Name your project to: author-api

Terminal: composer create-project --prefer-dist laravel/laravel author-api

After you poured water to make tea, the composer also created a project integrated laravel 7.12.0 (this is the latest version I use)

The initialization screen succeeds as follows:

Next, you add Laravel Passport, also very simple

cd path_of_project

composer require laravel/passport

The current version is: “laravel / passport”: “^ 9.2”

3. Config DB and Passport

Open the .env file to edit the db information you want the project you use

DB_DATABASE = laravel

DB_USERNAME = root

DB_PASSWORD =

Please replace the above 3 information.

Create Migrations:

  1. Employee table (username, email, name, pass)
  2. Job User (name, major, job, company)

With the 2 tables above we will create 2 migrations in turn as shown below.

Table Employees:

php artisan make:migration create_employees_table --create=employees

In migration you add the following code to initialize the table:

Table Jobs:

php artisan make:migration create_jobs_table --create=jobs

In the migration file, add:

After you have finished running the command and observe the result: php artisan migrate

Success! :

Create 2 corresponding models:

Config Laravel Passport

This is the most important step! I will do it slowly so you can watch it more carefully.

Open class App Employee

Add library declaration: use LaravelPassportHasApiTokens;

And add: use Notifiable, HasApiTokens;

Open class app / Providers / AuthServiceProvider and add the following:

AuthServiceProvider.php

By doing this, you have completed 80% of the installation of Passport can work already.

Next, open the config / auth file

Replace line 45 'driver' => 'token', => 'driver' => 'passport',

4. Initialize Authenticator Controller

php artisan make:controller API/BaseController

BaseController.php

php artisan make:controller API/EmployeeAuthor

EmployeeAuthor.php

Add Resource Job

php artisan make:resource JobRES

Initialize JobAll Controller

JobAll.php

Next you need to declare the routes so that the server can recognize the APIs you created above.

Open routes.api.php file

5. Run DEMO

So, the installation and coding project is now complete, you will run a demo to see the results

First you need to run the command: php artisan passport:install

It will generate 2 secret keys:

Personal access client created successfully.

Client ID: 1

Client secret: NcuUcYGj93eLqrLfH5TCAvChR6xpdA556Aqu61jv

Password grant client created successfully.

Client ID: 2

Client secret: eDnIkv4VXGKhhfT92iYOdso2BhVGTkGSGavItl7d

Next, you need to run the following command from the root project:

php artisan serve

You already have the domain to call the default api http://127.0.0.1:8000

Edit the config.auth.php file

Line 71: You need to set 'model' => AppEmployee::class,

Because we need authen for Employee model, not User as default.

Let’s test the API register now!

API – Register DONE

API – Create A Job

So you have created 1 Job IT for the user named ThanhViet. In fact you need to check the require information such as date of birth and email to identify the correct user (name = ThanhViet) who performed this insert for security purposes.

But in this demo, you can see that the access_token created is unique and must be required to make an api/job call, so it is quite secure information on my server already.

Note :

You must pass the Authorization parameter in Postman as follows:

Similar to other APIs you can actively explore!

6. Summary

Above is the part of using Laravel Passport to create RESTFUL API Authentication fully, I hope the article will bring you the usefulness. If you have any questions or questions, please leave them in the comment section below and I will try to answer as quickly as possible! Happy coding ^^

Share the news now

Source : Viblo