Creating Secure Login and Signup APIs in Laravel 10: A Step-by-Step Guide

Yash Kumar Prasad
4 min readOct 8, 2024

--

APIs are the backbone of modern applications, and security assurances are critical to protecting user data. In this guide, we will walk through building a secure login and registration API in Laravel 10, leveraging Sanctum for token-based authentication. By the end, you’ll have a fully functional authentication system that you can install in any application.

Prerequisites

  • Basic knowledge of Laravel.
  • Composer installed.
  • Basic understanding of RESTful APIs.
  1. Introduction

APIs provide seamless communication between front-end and back-end systems, especially in modern single-page applications (SPAs) and mobile applications. Laravel 10 provides an excellent tool for building secure and efficient APIs. In this tutorial, we’ll build APIs for user registration and login, implement authentication using Laravel Sanctum, and make sure everything is secure.

2. Setting Up Laravel 10

Step 1: Install Laravel

First, you need to install Laravel 10. Open your terminal and run:

composer create-project --prefer-dist laravel/laravel laravel-api-auth

Once installed, navigate into your project:

cd laravel-api-auth

Step 2: Configure the Database

Next, we need to set up our database. Open the .env file and update the database configuration:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_api_auth
DB_USERNAME=root
DB_PASSWORD=yourpassword

Run the following command to generate an application key:

php artisan key:generate

Step 3: Run Migrations

Laravel comes with a user model and migration by default. Run the following command to create the users table:

php artisan migrate

Your database is now ready!

3. Creating User Authentication APIs

In this section, we’ll create routes and controllers for user registration and login. Laravel’s default authentication system can be customized to suit API needs.

Step 1: Install Sanctum for API Authentication

Sanctum provides a simple way to issue API tokens for users without the complexity of OAuth. Install it by running:

composer require laravel/sanctum

Next, publish the Sanctum configuration:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

Then, run the Sanctum migration:

php artisan migrate

To enable Sanctum for API tokens, add Sanctum::usePersonalAccessTokenModel(); to your AppServiceProvider.

Step 2: Setting Up Sanctum Middleware

Update the api middleware group in app/Http/Kernel.php to include EnsureFrontendRequestsAreStateful:

use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;

'api' => [
EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],

This ensures that Sanctum works with stateful requests like SPAs.

4. User Registration API

Step 1: Create Routes

Open routes/api.php and define the registration route:

use App\Http\Controllers\AuthController;

Route::post('/register', [AuthController::class, 'register']);

Step 2: Create AuthController

Generate a controller for authentication:

php artisan make:controller AuthController

In AuthController.php, add the registration logic:

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
public function register(Request $request)
{
// Validate input
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
]);

if ($validator->fails()) {
return response()->json($validator->errors(), 400);
}

// Create user
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);

// Generate token
$token = $user->createToken('auth_token')->plainTextToken;

return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
}

This function validates the request, creates a new user, and returns an API token for the registered user.

5. User Login API

Step 1: Add Login Route

Define the login route in routes/api.php:

Route::post('/login', [AuthController::class, 'login']);

Step 2: Implement Login Logic

In AuthController.php, add the login method:

public function login(Request $request)
{
// Validate input
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);

// Check if user exists
$user = User::where('email', $request->email)->first();

// Check password
if (!$user || !Hash::check($request->password, $user->password)) {
return response()->json(['message' => 'Invalid credentials'], 401);
}

// Generate token
$token = $user->createToken('auth_token')->plainTextToken;

return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
]);
}

Here, we validate the login request, check the user’s credentials, and return a token if authentication is successful.

6. Adding Security Measures

Throttling

You can prevent abuse by limiting the number of requests using Laravel’s built-in throttling feature. This is already applied by default via the throttle:api middleware, but you can adjust the rate limits in config/api.php..

Middleware Protection

To protect routes from unauthenticated access, use the auth:sanctum middleware. For example, to protect a route:

Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:sanctum');

This ensures only authenticated users can access the route.

7. Testing APIs

Using Postman

You can test your APIs using Postman. Here’s how:

  • Register: Send a POST request to /api/register with name, email, and password in the body.
  • Login: Send a POST request to /api/login with email and password.
  • Authenticated Requests: Use the Bearer token received during login to authenticate further requests.

Handling Edge Cases

Test for common issues such as:

  • Missing or invalid fields.
  • Duplicate email registration.
  • Incorrect passwords during login.

Conclusion

In this guide, we created a simple but secure authentication scheme using Laravel 10 and Sanctum. We took the process of building registration and access APIs, creating tokens, and securing the process with middleware. Laravel’s robust framework makes it easy to build scalable and secure APIs for modern applications.

Be sure to explore the many features of Laravel to further enhance your API, such as password reset, email verification, and role-based access control.

Happy coding!

--

--

Yash Kumar Prasad
Yash Kumar Prasad

Written by Yash Kumar Prasad

Full-stack developer with a passion for crafting robust web solutions. Experienced in creating scalable applications that prioritize user experience.