Secure your REST API in 5 minutes with Laravel Sanctum

Secure your REST API in 5 minutes with Laravel Sanctum

Published
Jan 16, 2024
Written by
Benjamin Crozat
0
comments
2 minutes
read

Introduction to Laravel Sanctum and how it helps securing REST APIs

Laravel Sanctum is a package for Laravel that provides a simple way to secure your REST API. For instance, in case you want your users to be able to build services top of your application.

That being said, the official documentation is extensive and you probably don’t have that kind of time. So I hope my quick guide will serve you well.

Install Laravel Sanctum via Composer

The package now comes installed by default in any new Laravel application.

If for some reason you don’t have Laravel Sanctum in your project, install it using Composer:

composer require laravel/sanctum

Once done, publish Sanctum’s configuration and migration files:

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

Finally, run your database migrations:

php artisan migrate

Issue API tokens to your users

You need to let your users generate tokens to consume your API.

Add the Laravel\Sanctum\HasApiTokens trait in your User model:

namespace App\Models;

use Laravel\Sanctum\HasApiTokens; // [tl! ++]

class User extends Authenticatable
{
    use HasApiTokens; // [tl! ++]
}

You can issue a token using the createToken method:

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

Make sure to let the user know that the token is only shown once. If they lose it, they’ll have to generate a new one.

Protect your REST API routes with Sanctum’s auth guard

To secure your API routes, use the sanctum guard. This ensures that all incoming requests are authenticated:

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

Manage your users’ API tokens

Managing tokens is crucial for security. To revoke them, use:

// Revoke all tokens.
$user->tokens()->delete();

// Revoke a specific token.
$user->tokens()->where('id', $tokenId)->delete();

Conclusion

Securing your REST API with Laravel Sanctum is an effective way to manage authentication and prevent misuses without overcomplicating everything.

There’s a lot more to Laravel Sanctum and I encourage you to go read the official documentation.

About Benjamin Crozat
Benjamin Crozat

Hi! I’m from the South of France and I’ve been a self-taught web developer since 2006. When I started learning PHP and JavaScript, PHP 4 was still widely used, Internet Explorer 6 ruled the world, and we used DHTML to add falling snow on websites.

Being able to educate myself for free on the web changed my life for the better. Giving back to the community was a natural direction in my career and I truly enjoy it.

Therefore, I decided to take action:

  1. I launched this blog in September 2022 with the goal to be in everyone’s Google search. I get more than tens of thousands of monthly clicks from it and even more visits overall (my analytics dashboard is public by the way).
  2. I also started growing my X (formerly Twitter) account at the same time, which has now over 7,000 followers.
  3. All the content I write is free thanks to my sponsors.

I also want to be completely free with my time and make a living with my own products. In April 2024, I launched Nobinge, a tool to summarize and chat with your content, including YouTube videos.

Believe me, I’m just getting started!

0 comments

You need to be signed in to comment this post.
Sign in with GitHub