An API without authentication is like a house without a door. So, let's secure our API by adding an authentication system to it:
- Set up Sanctum Middleware
- Create a User Registration API
- Create a User Login API
Let's get secure!
Setting Up Authentication Middleware
Let's start by securing our API endpoint with a Middleware:
routes/api.php
// ... Route::group(['middleware' => 'auth:sanctum'], function () { Route::apiResource('categories', CategoryController::class); Route::apiResource('transactions', TransactionController::class);});Now, we can immediately try to make an API request using Postman:

This is good! However, we need to create a user registration and login API to authenticate our users.
Registering our First User
So, let's create a way to register a new user. For this, we need a new Controller:
php artisan make:controller Api/AuthControllerIn there, let's add a new method to register a user...
I would use the following code for the logout function. This way the tokens will be removed from the database.