Step-by-Step Guide to Implementing Laravel Passport in Laravel 10 for API Authentication

Yash Kumar Prasad
4 min readOct 15, 2024

Introduction

When building APIs in Laravel, having strong and secure authentication is vital. Laravel Passport gives a complete OAuth2 server implementation to your Laravel software, which makes it clean to implement API authentication. In this manual, we’ll walk via the method of setting up and implementing the Passport package in a Laravel 10 utility, focusing on API authentication.

By the cease of this educational, you will be able to configure Laravel Passport to control tokens on your API customers successfully.

Table of Contents

  1. What is Laravel Passport?
  2. Setting Up Laravel Passport in Laravel 10
  3. Configuring Passport in Laravel
  4. Using Passport for API Authentication
  5. Generating Access Tokens
  6. Conclusion

1. What is Laravel Passport?

Laravel Passport is an OAuth2 server and API authentication package designed for Laravel applications. It allows you to issue access tokens to your users without having to worry about the details of OAuth2 implementation. The package integrates seamlessly with the Laravel framework, and it’s perfect for securing your API endpoints.

Key features of Laravel Passport:

  • Full OAuth2 server implementation.
  • Easy-to-use token management.
  • Token-based authentication for APIs.
  • Built-in support for personal access tokens, client credentials, and password grant tokens.

2. Setting Up Laravel Passport in Laravel 10

To begin implementing Passport, you first need to install and configure it within your Laravel 10 project.

Step 1: Install Laravel Passport

Run the following command in your terminal to install the Passport package via Composer:

composer require laravel/passport

Step 2: Run Migrations

After installing Passport, you need to run the migrations that come with it. These migrations will create the necessary tables for Passport’s token management.

php artisan migrate

Step 3: Install Passport

Once the migrations are done, you can install Passport with the command below. This will generate the encryption keys needed to issue secure access tokens.

php artisan passport:install

This command will output several keys, including personal access client credentials and password grant client credentials. Keep these keys safe as they are essential for token management.

Step 4: Add Passport to the Auth Config

Next, you need to modify your config/auth.php file to use Passport’s TokenGuard for API authentication. Update the api driver under the guards section:

'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],

Step 5: Add HasApiTokens Trait to the User Model

In the User.php model, you need to include the HasApiTokens trait, which allows the model to generate access tokens for users.

use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
use HasApiTokens, Notifiable;
}

3. Configuring Passport in Laravel

After installing and setting up Passport, you’ll need to make a few additional configurations to ensure everything works smoothly.

Step 1: Register Passport Routes

You must register the Passport routes in your AuthServiceProvider. Open the app/Providers/AuthServiceProvider.php file and add the Passport::routes() method inside the boot function:

use Laravel\Passport\Passport;

public function boot()
{
$this->registerPolicies();
Passport::routes();
}

Step 2: Token Lifetimes (Optional)

By default, Passport tokens do not expire quickly. You can customize the lifetime of tokens by adding the following inside the boot method of the AuthServiceProvider:

Passport::tokensExpireIn(now()->addDays(15));
Passport::refreshTokensExpireIn(now()->addDays(30));
Passport::personalAccessTokensExpireIn(now()->addMonths(6));

This configures the expiration time of various token types.

4. Using Passport for API Authentication

With Laravel Passport fully installed, you can now implement API authentication using token-based access.

Step 1: Creating Routes for Authentication

In your routes/api.php file, define routes for registering and logging in users. Here's an example of two routes:

use App\Http\Controllers\API\AuthController;

Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);

Step 2: Implement Authentication Methods in the Controller

Create an AuthController using the command:

php artisan make:controller API/AuthController

In this controller, you can define the logic for user registration and login, as shown below:

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);

$user = User::create([
'name' => $validatedData['name'],
'email' => $validatedData['email'],
'password' => Hash::make($validatedData['password']),
]);

$token = $user->createToken('API Token')->accessToken;

return response()->json(['token' => $token], 200);
}

public function login(Request $request)
{
$credentials = $request->only('email', 'password');

if (Auth::attempt($credentials)) {
$user = Auth::user();
$token = $user->createToken('API Token')->accessToken;
return response()->json(['token' => $token], 200);
} else {
return response()->json(['error' => 'Unauthorized'], 401);
}
}
}

These methods allow users to register and login, generating an access token for each authenticated session.

5. Generating Access Tokens

To test your API authentication, use tools like Postman or cURL. For example, send a POST request to /login or /register with the necessary payload:

{
"email": "user@example.com",
"password": "password"
}

Upon successful login, you’ll receive a JSON response with the generated access token. You can then use this token in the Authorization header for subsequent API requests:

Authorization: Bearer {your-token}

6. Conclusion

In this article, we’ve gone through the step-by-step process of setting up and implementing Laravel Passport in a Laravel 10 application for API authentication. Passport simplifies token-based authentication for Laravel, allowing developers to build secure and scalable API services quickly.

With Laravel Passport, you can manage OAuth2 tokens efficiently, giving your API users secure and flexible access to your resources. Whether you’re building a small app or a large-scale API-driven service, Passport is a valuable tool to ensure your authentication is solid.

Do you have questions or feedback about Laravel Passport? Let me know in the comments below!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Yash Kumar Prasad
Yash Kumar Prasad

Written by Yash Kumar Prasad

Full-stack developer with a passion for crafting robust web solutions. Experienced in creating scalable applications that prioritize user experience.

No responses yet

Write a response