Create API Authentication With Laravel Passport

Introduction

Nowadays, there is no way to avoid the topic of RESTful APIs when building back-end resources for a mobile application or developing a web application. An API is an interface, that allows two software programs to communicate with each other. Notably, it does not maintain a session state between requests, hence, you will need to use tokens to authenticate and authorize users of your application.

For web developers, it’s important for us to authenticate our users via API Request. In Laravel itself, besides its full-stack development, we have many options on how to authenticate the requests. 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.

What We’ll Build

To understand API security, we will build an API that provide authentication methods and CRUD operation of posts :

  • Registering user
  • Logging in and out
  • Perform CRUD operation for posts.

Setting Up a Laravel Web Service Project

Let's begin to create our fresh Laravel application for API Authentication using Passport.

This will create a new folder named LaravelPassportApi containing our Laravel application. Now would be a good time to start the Laravel application to make sure everything is working as expected:

Database Configuration

Let's configure database for our application. If you have don't have any database then create a new one. After creating database open .env file from root directory of your project. if .env file is missing from project then copy content from .env.example and create file. .env file defines many common environment variables

Replace * with your actual configuration in upper code.

After database configuration, run database migrations :

Installation and Setup of Laravel Passport

First of all, let’s add Laravel Passport to it. We need to install Laravel Passport into our application using Composer:

Passport will need to store OAuth2 clients and access tokens in some database tables, so it creates migrations for the tables during installation. So next thing we need to do is running migrations :

To generate secure access tokens for your application, Passport requires some encryption keys and two clients known as Laravel Personal Access Client and Laravel Password Grant Client. To create these keys and encryption clients, run the following command:

Passport package comes with some routes used to issue and revoke access tokens. To register and use these routes, we need to call the Passport::routes() method inside the boot method in your AuthServiceProvider.

Navigate to App\Providers\AuthServiceProvider and update it.

After changes into AuthServiceProvider we are ready to to handle all authentication and authorization processes within your application.

Now we have to set which authentication guard will handle incoming API request. Open config/auth.php file and make following changes :

One very last thing we need to update User model before starting api development.

Open the app/Models/User.php file and add the following modifications:

Create Register and Login

Now, our setup is complete and we can perform API requests. First of all, we will create API end points for authentication.

In this example, we will just create register and login functionality with API. so we will need a controller to perform those actions. Enter below command to create new controller for API authentication :

It will create new controller. In this controller, we will create two functions which handles login and register functionality.

Navigate to App\Http\Controller\ApiAuthController and update as below.

Register function will take request object which contains name, email, and password for the user. First of all, it will validate the user request and if the request is valid then it will create a user and assign an authentication token to it. While on the other end login function will check credentials and return a token as a response.

In both function, we will return type and token as response with passport authentication token type is Bearer by default. We need this token in a further API request to validate the user is authorized to perform those actions.

Create Posts Functionality

Before performing post CRUD, we need to define database table design and create database table for posts. Let's create posts model and migration using below command :

This command will create 2 files first one is model and second is migration. You will see posts migration file in database/migrations/timestamp_create_posts_table.php and App/Models/Post.php.

Let's change migration file to store relevant information like user, title of post and post details.

Here, we have defined user column as foreign key for user table, title as string and description as text data type. while creating post we will ask user to enter title and description for post.

Next, open the app/Models/Post.php file and add the following values inside the $fillable array and create relation between user and post table.

Let's define has many relation between user and posts for further usage. Open User model and add following lines to it.

At last, run the migration by using the below command :

It will create posts table into database. New we can need to create controller to handle CRUD operation for posts. Open terminal and enter below command :

Add the following code in app/Https/Controllers/PostController.php file.

Here, we have created CRUD functionality for posts. Those function will returns JSON data as response.

Define API Routes

Now, we will define API routes for register, login and post CURD functionality. Go to routes/api.php file and make following changes.

Test Laravel Passport API

Now, we completed all necessary steps to create Laravel passport API. It's time to test our API. First of run application server using below command :

Here, we will use Postman for testing API end points. So open postman and create new project or request.

Before sending postman request you need to set header as "Accept": application/json. See below picture as refreance :

Postman Header for Accept JSON

Register API

First of all, we will check register api. As we know we need name, email and password to register user into our application then we need to pass it as paramenter.

User Register API request for Laravel Passport

Please verify method POST for register user end point. As you can see in image as response you will get token and it's type. We will need them into login request or post related operations.

Login API

Now user is created. We can use credentials and login to user account using login end point. We need to pass email and password as request parameter.

User login API request for Laravel Passport

Post APIs

Register & login will also return token on success. We will pass that token while calling further APIs. To set up token with request open Authorization tab and select Bearer as type. Then place token into token field. Please check below image as reference for requesting all post end point.

Laravel Passport Authentication get data

Now you can check all endpoints by passing token and selecting method as per request.

Conclusion

Now, we have completed the Laravel Passport API authentication example with CRUD operation. Here, we have checked every aspect needed to build secure REST APIs in Laravel using Passport Authentication. Perform step by step setup to overcome errors and if you still have any doubts feel free to place a comment.


Share your thoughts

Ask anything about this examples