Creating a secure REST API is essential for any modern web application that interacts with client-side applications or third-party services. Laravel, one of the most popular PHP frameworks, makes API development seamless with Laravel Sanctum, a lightweight authentication package designed for simple API token management and SPA authentication.
Laravel Sanctum provides an easy-to-implement authentication system, making it an excellent choice for securing your API. If you are looking for professional Laravel development services, implementing authentication with Sanctum ensures that your application is protected against unauthorized access and security threats.
In this step-by-step guide, we will walk through setting up Laravel Sanctum and building a secure REST API with authentication.
Prerequisites
Before we start, make sure you have the following:
- PHP 8 or higher installed
- Composer installed
- Laravel 10 or higher installed
- MySQL or any other preferred database
Step 1: Install Laravel Sanctum
To get started, install Laravel Sanctum using Composer:
composer require laravel/sanctum
Next, publish the Sanctum configuration file:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Run the database migration command to create the necessary tables:
php artisan migrate
Step 2: Configure Sanctum Middleware
To enable Sanctum’s authentication middleware, add it to your API middleware in app/Http/Kernel.php:
protected $middlewareGroups = [ 'api' = [ \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ],];
Also, add the HasApiTokens trait to your User model:
namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable;use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable{ use HasApiTokens, Notifiable;}
Step 3: Setting Up Authentication Routes
Now, define authentication routes in routes/api.php:
use App\Http\Controllers\AuthController;use Illuminate\Support\Facades\Route; Route::post('/register', [AuthController::class, 'register']);Route::post('/login', [AuthController::class, 'login']);Route::middleware('auth:sanctum')-post('/logout', [AuthController::class, 'logout']);
Step 4: Creating the Authentication Controller
Generate an authentication controller using Artisan:
php artisan make:controller AuthController
Inside AuthController.php, implement the authentication methods:
namespace App\Http\Controllers; use Illuminate\Http\Request;use Illuminate\Support\Facades\Hash;use Illuminate\Support\Facades\Auth;use App\Models\User; class AuthController extends Controller{ public function register(Request $request) { $request-validate([ 'name' = 'required|string', 'email' = 'required|email|unique:users', 'password' = 'required|min:6', ]); $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' = 'Unauthorized'], 401); } $user = Auth::user(); $token = $user-createToken('auth_token')-plainTextToken; return response()-json(['access_token' = $token, 'token_type' = 'Bearer']); } public function logout(Request $request) { $request-user()-tokens()-delete(); return response()-json(['message' = 'Logged out successfully']); }}
Step 5: Protecting API Routes with Sanctum Middleware
Now, secure your API routes by adding the auth:sanctum middleware in routes/api.php:
Route::middleware('auth:sanctum')-get('/user', function (Request $request) { return $request-user();});
This ensures that only authenticated users can access the /user endpoint.
Step 6: Testing the API
Use Postman or any API testing tool to verify your setup:
- Register a new user by sending a POST request to /register with name, email, and password.
- Log in by sending a POST request to /login and receive a token.
- Access protected routes by including the token in the Authorization header (Bearer token).
- Log out by sending a POST request to /logout with the token.
Conclusion
Laravel Sanctum makes it easy to implement authentication and secure your API. By following this step-by-step guide, you have successfully built a secure REST API with Laravel and Sanctum, ensuring that only authenticated users can access protected resources.
If you need expert Laravel development services, integrating secure API authentication is just one of the many ways to enhance your application’s security and performance. Start building secure APIs today and scale your Laravel application with confidence!