Authenticating Laravel API Using Passport

Tram Ho


Authentication and security are crucial in today’s application building and management process. In this tutorial, we will learn about Laravel APIs Using Passport validations. Api is known to authenticate a user using a session between requests. With the Laravel framework, authenticated api are simpler using a single Oauth2 package Laravel passport.

Setup a Laravel project

Install the laravel/passport package

Next they need to update the .env file and add a connection to the databse and run the migrate to create the necessary tables.

After running, you can see the following results:

Configuring Passport

To implement api authentication we need to use the HasApiTokens passport provided for the models of the application.

Update App / User.php models

Next we will call Passport::routes() in boot() at the app/Providers/AuthServiceProvider.php

Once setup is complete, the next step is to set the default passport as the API authentication method. We will edit the config/auth.php file

Building a Simple API Authentication System using Passport

We now have the passport installed and configured in the project. We need to create a UserController to register and login to the application. Update the routes/api.php file

Create the controller by running the following command:

The above command will create the UserController.php file in the App / Http / Controllers. Open it and add the signup and login method

Run the application server by command:

Test result

Register [POST]: Login [POST]:

My post is over here and see you again in the next articles.?


Share the news now

Source : Viblo