Securing Your E-commerce API with Laravel Sanctum: A Complete Guide
Sanctum is Laravel’s official authentication package that makes it easy to secure your API endpoints using various authentication mechanisms. In this blog, we will explore how to use Laravel Sanctum to secure an e-commerce API. We will start by installing Laravel and Sanctum, then proceed to build our API with endpoints that handle user authentication and product listing.
Prerequisites
Before we get started, ensure you have the following software installed on your computer:
- PHP 7.4 or higher
- Composer
- Laravel 8
- MySQL
Installation
Let’s start by creating a new Laravel project by running the following command:
laravel new ecommerce
Next, navigate to the project directory and install Sanctum using Composer:
cd ecommerce
composer require laravel/sanctum
Once installed, we need to run the Sanctum migrations:
php artisan migrate
Now, we can proceed to set up Sanctum in our Laravel project.
Setting up Sanctum
In Laravel, Sanctum is configured in the config/auth.php
file. To enable Sanctum, add the following configuration to the guards
array:
'sanctum' => [
'driver' => 'sanctum',
'provider' => 'users',
],
Next, add the following configuration to the providers
array:
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
This tells Laravel to use Sanctum as the authentication driver for the users
guard and to use the User
model for authentication.
To generate the necessary authentication scaffolding, run the following command:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
This will create the necessary authentication files, including the auth.php
configuration file, the CreatePersonalAccessToken
migration, and the PersonalAccessToken
model.
Finally, add the HasApiTokens
trait to the User
model:
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
// ...
}
This trait provides the createToken
method that we will use to generate personal access tokens.
Building the E-commerce API
Now that we have set up Sanctum, we can proceed to build our e-commerce API. In this example, we will create endpoints that handle user authentication and product listing.
User authentication
Let’s start by creating an endpoint that allows users to authenticate and generate a personal access token. To do this, we will create a LoginController
that handles user authentication:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
$user = Auth::user();
$token = $user->createToken('auth-token')->plainTextToken;
return response()->json(['token' => $token]);
}
return response()->json(['error' => 'Invalid login credentials'], 401);
}
}
This endpoint accepts an email and password, authenticates the user, and generates a personal access token using the createToken
method.
To secure this endpoint, we need to add the auth:sanctum
middleware to the route that handles user authentication. This middleware will ensure that the endpoint can only be accessed by authenticated users with a valid personal access token. Here's how we can define the route:
Route::post('/login', [LoginController::class, 'login'])->middleware('auth:sanctum');
Product Listing
Now let’s create an endpoint that lists all the products in our e-commerce store. We will create a ProductController
that retrieves the list of products from the database and returns it as a JSON response:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
class ProductController extends Controller
{
public function index()
{
$products = Product::all();
return response()->json(['products' => $products]);
}
}
To secure this endpoint, we need to add the auth:sanctum
middleware to the route that handles product listing. Here's how we can define the route:
Route::get('/products', [ProductController::class, 'index'])->middleware('auth:sanctum');
In this blog, we have seen how to use Laravel Sanctum to secure an e-commerce API. We started by installing Laravel and Sanctum, then proceeded to set up Sanctum in our Laravel project. We then built our API with endpoints that handle user authentication and product listing, securing them with the
auth:sanctum
middleware. With this knowledge, you can now build your own secure APIs using Laravel Sanctum.