When building modern web applications or mobile apps, a robust and secure REST API is essential. Laravel, a popular PHP framework, makes it incredibly easy to build APIs. But an API without proper security is a disaster waiting to happen.
In this tutorial, we will walk through the process of creating a REST API using Laravel and securing it with Laravel Sanctum, a featherweight authentication system for SPAs, mobile applications, and simple token-based APIs.
Step 1: Setting Up the Laravel Project
First, let's create a fresh Laravel project and set up our database connection. Open your terminal and run:
composer create-project laravel/laravel api-sanctum-demo
cd api-sanctum-demo
Next, configure your .env file with your database credentials. Once done, migrate the default database tables:
php artisan migrate
Step 2: Installing and Configuring Sanctum
Laravel Sanctum provides a simple way to authenticate users via API tokens. To install it, run:
composer require laravel/sanctum
Publish the Sanctum configuration and migration files:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Run the migration to create the necessary table for storing API tokens:
php artisan migrate
Finally, we need to instruct the User model to use Sanctum. Open app/Models/User.php and add the HasApiTokens trait:
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
// ...
}
Step 3: Creating the Authentication Controller
We need a way for users to register and log in to receive their API tokens. Let's create an AuthController:
php artisan make:controller AuthController
Open app/Http/Controllers/AuthController.php and implement the register and login methods:
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function register(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
public function login(Request $request)
{
if (!Auth::attempt($request->only('email', 'password'))) {
return response()->json([
'message' => 'Invalid login details'
], 401);
}
$user = User::where('email', $request['email'])->firstOrFail();
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
}
Step 4: Defining API Routes
Now, let's register our routes. Open routes/api.php. We will define public routes for registration and login, and a protected route that requires authentication:
use App\Http\Controllers\AuthController;
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
// Public routes
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
// Protected routes
Route::middleware('auth:sanctum')->group(function () {
Route::get('/user', function (Request $request) {
return $request->user();
});
});
Step 5: Testing the API
You can use tools like Postman or Insomnia to test your new API.
- Register: Send a POST request to
/api/registerwith name, email, and password. You will receive an access token. - Login: Send a POST request to
/api/loginwith your credentials to get a new token. - Access Protected Route: Send a GET request to
/api/userand include the headerAuthorization: Bearer YOUR_TOKEN_HERE. You should see your user details.
Conclusion
Securing your API is a critical step in development. Laravel Sanctum simplifies this process significantly, providing a straightforward approach to API token management. With just a few steps, we successfully built and secured a REST API in Laravel.