Courses

[NEW] React Native Mobile App with Laravel 12 API

API Authentication

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Secure API routes with Laravel Sanctum middleware in route groups
- Create a user registration endpoint that validates input and returns API tokens
- Implement login functionality to authenticate users and generate access tokens
- Add logout capability to revoke user tokens when sessions end

Link to the repository

[Only for premium members]

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 19 text lessons of this course? (91 min read)

You also get:

  • 77 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord