Building API Authentication with Laravel Passport

Building API Authentication

Introduction

API stands for Application Programming Interface. It is a  code or interface in Java that allows smooth communication Among software or programs, in this case using the same packages. RESTful APIs are fundamental for modern JavaScript frameworks or building mobile applications. The user needs tokens for authorization or authentication of the application. In the case of software development, API handles data through HTTP requests and manages CRUD operations.

Laravel is a platform that makes the building of APIs extremely easy. By using the Laravel passport, one can quickly secure the backend of the applications by authenticating the users through API. In the API ecosystem, one does not maintain the session state among requests. This article will guide you step by step to provide an additional layer of security to your Laravel APIs.

Laravel Passport: what is it?

In simple words, Laravel passport is an API authentication package and an OAuth2 server. It is a platform containing a substantial amount of boilerplate codes for the authentication of users. To implement the packages, including functions for generating tokens, migration tables, or authentication of Middleware,  one just needs to adjust some basic configurations on the Laravel passport platform. Software companies have a demand for people with vast knowledge of Laravel and are looking forward to hire Laravel developers.

Requirements:

  • COMPOSER – globally installed to manage dependencies
  • POSTMAN – to test the endpoints
  • Basic knowledge of application building.

Installing Laravel Passport:

  • For installation of Laravel Passport, first, you need to run the mentioned.

command:

composer require laravel/passport

  • Once the installation of the passport package is successful, the following step is passport migration for storing the tokens in new tables.

php artisan migrate

  • After the migration of the tables, running the following command will install it completely.

php artisan passport:install

  • Code for the configuration of the passport module; you need to open the app/Models/User.php file to include the HasApiTokens trait in the user model.

In the following section, we will configure the passport’s routes controller of authentication.

  • You have to add the Passport::routes method in the AuthServiceProvider to generate the necessary routes. We can specify the default lifetime expiry date of personal access tokens that we are issuing to the users using the boot() function.
  • We need to set the passport as the API authentication guard. By modifying the config/auth.php, henceforth, all applications can use Passport’s TokenGuard to authenticate all incoming API requests.
  • Our primary focus is ensuring that only authenticated users can access the specified routes. To focus on this aspect, you need to protect the /user and /logout endpoints and keep the /login and /signup  endpoints publicly accessible.

Next, we will create routes by adding routes in the routes/api.php file.

We also need to create an API controller for the REST API in Laravel.

  • For this purpose, we need to run the below-mentioned Artisan command to create a new controller.

🌕 php artisan make: controller ApiController.php

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Traits\ApiResponser;
use Illuminate\Http\Request;
use Laravel\Passport\Passport;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
use ApiResponser;

public function login(Request $request)
{
$attr = $this->validateLogin($request);

if (!Auth::attempt($attr)) {
return $this->error(‘Credentials mismatch’, 401);
}

return $this->token($this->getPersonalAccessToken());
}

public function signup(Request $request)
{
$attr = $this->validateSignup($request);

User::create([
‘name’ => $attr[‘name’],
’email’ => $attr[’email’],
‘password’ => Hash::make($attr[‘password’])
]);

Auth::attempt([’email’ => $attr[’email’], ‘password’ => $attr[‘password’]]);

return $this->token($this->getPersonalAccessToken(), ‘User Created’, 201);
}

public function user()
{
return $this->success(Auth::user());
}

public function logout()
{
Auth::user()->token()->revoke();
return $this->success(‘User Logged Out’, 200);
}

public function getPersonalAccessToken()
{
if (request()->remember_me === ‘true’)
Passport::personalAccessTokensExpireIn(now()->addDays(15));

return Auth::user()->createToken(‘Personal Access Token’);
}

public function validateLogin($request)
{
return $request->validate([
’email’ => ‘required|string|email|max:255’,
‘password’ => ‘required|string|min:6’,
]);
}

public function validateSignup($request)
{
return $request->validate([
‘name’ => ‘required|string’,
’email’ => ‘required|string|email|max:255|unique:users’,
‘password’ => ‘required|string|min:6|confirmed’,
]);
}
}

Here, in the signup() function, you need to create a new user according to the data requested by validating the data provided.

  • To generate a token, we can call a function getPersonalAccessToken().

The lifetime of the token can be stretched when we set the remember_me value to ‘true.’

  • Since the Passport Middleware protects the /user endpoint, we will always have access to the Auth::user() function.

After we have successfully created a controller for authentication, it is time to test the REST API. You can either use a virtual host for testing or test it on the PHP development server.

Generally, we use tools like Postman to test our API endpoints.

To initiate this process, you shall start by getting an access token for an already registered user. You can send a GET request to “API/login” by incorporating the email and password as parameters. If not registered,

  • Registration of API: Open The postman application and define “Accept”: application/JSON
  • Login Passport API: used to copy the bearer token and set it in the header section of the app. For logging in, you will have to check out the Laravel passport endpoint.
  • We need to set accurate authenticity to execute the CRUD operations. You will be receiving an access token after a successful registration. This access token’s manifestation establishes coherence with authorization to ensure secure transmission of data with the server.

You should save the access token as a

Bearer token in the authorization header.

Conclusion

Ultimately we completed The Laravel passport API tutorial. You can go through all the described foundation steps to build on this and design a secure API using Laravel passport. Mastering this process of developing secure APIs in Laravel Passport can ensure you get hired as a Laravel developer. Errors may arise in any step, depending on the code and its application, but through a continuous process of trial and error, one can develop a secure API quickly.


Subscribe to Our Newsletter

Related Articles

Top Trending

best gaming chairs for posture
The 6 Best Gaming Chairs for Posture Support in 2026
On This Day February 13
On This Day February 13: History, Famous Birthdays, Deaths & Global Events
Benefits of Slow Living in 2026
Why "Slow Living" Is The Antidote To 2026 Burnout: Revive Yourself!
Best countertop composters
The 4 Best Countertop Composters Reviewed: Go Green!
The Fallen Banyan- A Shadow That Still Shelters Our Souls
The Fallen Banyan: A Shadow That Still Shelters Our Souls

Fintech & Finance

7 Best Neobanks for Cashback Rewards in 2026
7 Neobanks Offering the Best Cashback Rewards in 2026
10 Influential Crypto Voices to Follow in 2026
10 Most Influential Crypto Voices to Follow in 2026: The Ultimate Watchlist
10 Best No-Foreign-Transaction-Fee Cards for Travelers
10 Best No-Foreign Transaction-Fee Credit Cards for Travelers
Best Business Credit Cards for Ecommerce
Top 5 Business Credit Cards for E-commerce Owners
budget apps that sync with your bank
10 Best Budgeting Apps That Sync With Your Bank [2026 Edition]

Sustainability & Living

top renewable energy cities 2026
10 Cities Leading the Renewable Energy Transition
Editorialge Eco Valentine T-shirts
Wear Your Heart Green: Editorialge Eco Valentine T-Shirts & Hoodies Review
Top 5 Portable Solar Generators for Camping in 2026
Top 5 Portable Solar Generators for Camping in 2026: Field-Tested Reviews
Water-Saving Habits
Water-Saving Habits That Actually Make a Difference: Transform Your Life!
clean tech breakthroughs
The Top 6 Clean Tech Breakthroughs from Late 2025 You Probably Missed!

GAMING

best gaming chairs for posture
The 6 Best Gaming Chairs for Posture Support in 2026
15 Cozy Games to Start Your New Year Relaxed
15 Cozy Games to Start the New Year Relaxed and Happy
console quality mobile games
5 Mobile Games That Actually Feel Like Console Experiences of 2026
best monitors for RTX 5000 series
Top 10 Gaming Monitors for the New Graphics Cards of 2026
Narrative Design hero's journey
Narrative Design in 2026: Moving Beyond the "Hero's Journey"! A Revolution Awaits!

Business & Marketing

Best Business Credit Cards for Ecommerce
Top 5 Business Credit Cards for E-commerce Owners
Top 6 Marketing Automation Tools With Best AI Integration
Top 6 Marketing Automation Tools With Best AI Integration
Corporate Social Responsibility
Corporate Social Responsibility: Why Employees Demand Action, Not Words
8 SaaS Trends Watching Out for in Q1 2026
8 Defining SaaS Trends to Watch in Q1 2026
How To Win Chargebacks
Mastering Dispute Resolution: How to Win Chargebacks in 2026 [Insider Tips]

Technology & AI

Best water filtration systems
The 4 Best Water Filtration Systems for You and Your Family
Best dedicated server providers for high-traffic sites
The 5 Best Dedicated Server Providers for High-Traffic Sites in 2026
Best crypto tax software
The 5 Best Crypto Tax Software Tools for the 2025 Tax Year. No More Mistakes
How to Install Mozillod5.2f5
Step-by-Step Guide: How to Install Mozillod5.2f5 and Firefox Successfully
best monitors for RTX 5000 series
Top 10 Gaming Monitors for the New Graphics Cards of 2026

Fitness & Wellness

Benefits of Slow Living in 2026
Why "Slow Living" Is The Antidote To 2026 Burnout: Revive Yourself!
JOMO outperforming FOMO
The Joy of Missing Out: Why JOMO is Outperforming FOMO in 2026
Dopamine Detox
Dopamine Detox 2.0: Reclaiming Attention in an Algorithm-Heavy World
The 7 Best Employee Wellness Apps for 2026
The 7 Best Employee Wellness Apps for 2026: A Complete Guide for HR Leaders
Sukanta Kundu Spinal Surgery Recovery
The Weight of the World: From a Broken Spine to a Miraculous Resurrection