Skip to main content

API Authentication

Premium
4 min read

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/AuthController

In there, let's add a new method to register a user...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (30 h 21 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

PV
Paul van Vulpen ✓ Link copied!

I would use the following code for the logout function. This way the tokens will be removed from the database.

// Logout
public function logout(Request $request)
{
$request->user()->tokens()->delete();
 
return response()->noContent();
}

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.