Laravel Passport, Create REST API With Authentication

Abdou Mjr
Abdou Mjr
May 11 · 4 min read

Application Program Interfaces, APIs, are snippets of code that allow one software application to talk to another, providing a common language. Whether allowing seamless experiences for end users across multiple applications, or allowing data from one application to be fed into another, APIs have revolutionised in the last years.

If you are a beginner and you are learning and figuring out how to make apis and secure them, then you came to the right place, in this article i will show you how to set up an api authentication.

What is passport ?

Laravel Passport is a full OAuth2 server implementation, it was built to make it easy to apply authentication over an API for laravel based web applications.

Lets start

After setting up laravel and installing composer please follow the following steps:

1- Install Passport via the Composer package manager:

the passport package will register its own database migrations.

2- Migrate the passport tables:

3- Install passport:

This command will create the encryption keys needed to generate secure access tokens.

4- Configuring passport:

add the Laravel\Passport\HasApiTokens trait to your App\Usermodel.

→ /project/app/User.php

Call Passport::routes method within the boot method of your AuthServiceProvider

→ /project/app/Providers/AuthServiceProvider.php

Set the driver option of the api authentication guard to passport

→ /project/config/auth.php

5- Creating the routes


6- Creating the controller

then just copy and paste the code below to your AuthController :

Before your application can issue personal access tokens, you will need to create a personal access client:

You need to create a personal access token

Finally, let’s try our register and login functionality :

For me, i’m using insomnia for HTTP-based APIs, to send http requests.

By sending a register request with all the data needed we can see a success response from our api , with a special token, we can use this token to communicate with the api.

Now, after that if we disconnect or the token has expired we can login again and get our token, throw the login api :