Deprecated: Creation of dynamic property Yoast\WP\SEO\Premium\Generated\Cached_Container::$normalizedIds is deprecated in /home/u812831811/domains/digitalwebport.com/public_html/wp-content/plugins/wordpress-seo-premium/src/generated/container.php on line 27
Laravel Sanctum API Auth: A Beginner's Guide

Easy Laravel Sanctum API Authentication: A Beginner’s Guide

easy-laravel-sanctum-api-authentication-a-beginners-guide

Table of Contents

Introduction to Laravel Sanctum API Authentication

Securing your APIs is paramount in modern web development. Laravel Sanctum provides a lightweight authentication system specifically designed for Single Page Applications (SPAs), mobile applications, and simple APIs. This guide offers an easy-to-understand introduction to Laravel Sanctum API Authentication, perfect for beginners who want to quickly implement secure authentication in their Laravel projects.

In this Laravel Sanctum API Authentication Tutorial, we’ll walk you through the entire process, from installation to implementation, ensuring you have a solid understanding of how it works and how to use it effectively. We’ll focus on making the process as straightforward as possible, removing any unnecessary complexity.

Why Choose Laravel Sanctum for API Authentication?

Laravel offers several authentication options, but Sanctum shines in specific scenarios:

  • Lightweight: It’s easier to configure than other heavier solutions like Laravel Passport.
  • SPA and Mobile-Friendly: Sanctum is designed to authenticate requests from SPAs or mobile applications using cookies or tokens.
  • Simple APIs: It’s suitable for APIs that don’t require OAuth2 complexity.

If you are developing a laravel scalable web application that needs token-based API authentication, Sanctum offers simplicity and security. For understanding other security features, refer PHP security best practices for developers

Prerequisites

Before we begin, ensure you have the following:

  • A Laravel project (version 8 or later).
  • Composer installed.
  • A database connection configured.

Step-by-Step Guide to Implementing Laravel Sanctum API Authentication

Step 1: Installation

First, install Laravel Sanctum using Composer:

composer require laravel/sanctum

Step 2: Publish Configuration and Migrations

Next, publish the configuration and migration files:

php artisan vendor:publish --provider="LaravelSanctumSanctumServiceProvider"

This command will create a `sanctum.php` configuration file in your `config` directory and a migration file. Run the migrations to create the necessary database table:

php artisan migrate

Step 3: Configure the User Model

In your `AppModelsUser` model, use the `HasApiTokens` trait:

namespace AppModels;

use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use LaravelSanctumHasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    // ... rest of your User model
}

Step 4: Create API Routes

Define your API routes in `routes/api.php`. For example:

use IlluminateSupportFacadesRoute;
use AppHttpControllersAuthController;

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

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/user', function (Request $request) {
        return $request->user();
    });
    Route::post('/logout', [AuthController::class, 'logout']);
});

The `auth:sanctum` middleware protects the `/user` route, ensuring only authenticated users can access it. For more information on authentication, visit Authentication articles.

Step 5: Create AuthController

Create an `AuthController` to handle registration, login, and logout. Here’s an example:

namespace AppHttpControllers;

use AppModelsUser;
use IlluminateHttpRequest;
use IlluminateSupportFacadesHash;
use IlluminateSupportFacadesAuth;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:6',
        ]);

        $user = User::create([
            'name' => $validatedData['name'],
            'email' => $validatedData['email'],
            'password' => Hash::make($validatedData['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' => 'Invalid login credentials'], 401);
        }

        $user = User::where('email', $request['email'])->firstOrFail();

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

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

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();

        return response()->json(['message' => 'Successfully logged out']);
    }
}

Step 6: Testing the API

You can test your API endpoints using tools like Postman or Insomnia. Send a POST request to `/register` with the required data to create a new user. Then, use the returned token to access the `/user` endpoint by including the `Authorization` header with `Bearer `. After successful authentication, you can even consider to create an e-commerce website. Read the following guide on create e-commerce website with Laravel

Advanced Topics and Considerations

Token Expiration

Sanctum doesn’t automatically handle token expiration. You might want to implement a mechanism to expire tokens after a certain period. One approach is to add a `expires_at` column to the `personal_access_tokens` table and update it when a token is created. You can then create a middleware to check if the token is expired before allowing access.

SPA Authentication with Cookies

For SPAs, Sanctum can use cookies instead of tokens. Configure your `config/sanctum.php` file accordingly. This requires your SPA and API to be on the same domain or subdomain. The following guide can help you with migrate website from PHP to Laravel

Securing Your API Further

Consider implementing additional security measures, such as rate limiting and input validation, to protect your API from abuse. For example, you can use Laravel’s built-in validation rules. Sanctum is an awesome framework when paired with an intuitive Admin Panel. Take a look at this Laravel nova admin panel tutorial.

Conclusion

Laravel Sanctum API Authentication is a simple yet powerful way to secure your APIs in Laravel. This Laravel Sanctum API Authentication Tutorial has provided a solid foundation for implementing secure Laravel API with Sanctum. By following these steps, you can easily protect your API endpoints and ensure that only authenticated users can access them. Remember to explore more advanced features as your application grows and requires more complex authentication needs. You can explore additional OWASP to ensure your web applications are secure and safe to use. Also learn more about Laravel Sanctum official documentation for more details.

If you like to create asynchronous job process, consider this useful guide laravel queue job processing basics.

Share On:
Picture of Jaspreet Singh
Jaspreet Singh
With over 10 years of experience as a website developer and designer, Jaspreet specializes in PHP, Laravel, and WordPress development. Passionate about sharing knowledge, Jaspreet writes comprehensive guides and tutorials aimed at helping developers—from beginners to experts—master web development technologies and best practices. Follow Jaspreet for practical tips, deep-dive technical insights, and the latest trends in PHP and web development.

Leave a comment

Your email address will not be published. Required fields are marked *

Latest Posts

Introduction to Web Development Costs in Toronto For businesses operating in Canada’s economic hub, establishing...

Introduction to Content Strategy and Keyword Research In the ever-evolving landscape of Digital Marketing, the...

Introduction to Atlanta Falcons Football Welcome to the world of the Dirty Birds! If you...

Introduction to Laravel Hosting on DigitalOcean Laravel has cemented its position as the most popular...

Introduction to Troubleshooting WordPress Site Issues Easily WordPress is the most popular content management system...

Find Your Local Custom Web Designer in Toronto for Unique Branding & Business Growth In...