DEV Community

Yasser Elgammal
Yasser Elgammal

Posted on

Dive into Laravel Sanctum Token Abilities

Laravel has great feature including in Sanctum, that allow to identify logged user and handle the authorize process through token,

This feature is called Sanctum Token Abilities

By using Sanctum Token Abilities you can With Laravel sanctum abilities you can specify ability once you create token,

You can use this ability to manage roles and routes due to specific abilities,

For example, you can use Sanctum Token Abilities to set routes that are accessible only to users with specific abilities. You can also perform actions based on a user's abilities, such as showing or hiding certain features or data.

It's simple and you can use it if you don't have multiple or complex roles

Let's practise with example:

1- Add following Middlewares lines to $middlewareAliases inside App\Http\Kernel

'abilities' => \Laravel\Sanctum\Http\Middleware\CheckAbilities::class,
'ability' => \Laravel\Sanctum\Http\Middleware\CheckForAnyAbility::class,
Enter fullscreen mode Exit fullscreen mode

2- Assign ability to user with poweful sanctum token by usign this:

$user->createToken('token-name', ['admin'])->plainTextToken;
Enter fullscreen mode Exit fullscreen mode

3- Now we can protect our routes, by specifying abilites

In this example, we're protecting the /admin/index route so that only users with the [moderator & admin] ability can access it.

Route::middleware(['auth:sanctum','abilities:moderator,admin'])->prefix('admin')->group(function () {
        Route::get('index', [AdminController::class, 'index']);
    });
Enter fullscreen mode Exit fullscreen mode

In this example, we're protecting the /admin/index route so that only users with the [moderator or admin] ability can access it, it means or user has at least one with access the route.

Route::middleware(['auth:sanctum','ability:moderator,admin'])->prefix('admin')->group(function () {
        Route::get('index', [AdminController::class, 'index']);
    });
Enter fullscreen mode Exit fullscreen mode

Also, we can check if user token has a specific ability for example through our controller,

        if (auth()->user()->tokenCan('admin')) {
            dd('Hello Admin');
        }
Enter fullscreen mode Exit fullscreen mode

Summary:
Sanctum Token Abilities is a feature of the Laravel Sanctum package that allows you to specify abilities for a token when it's created. These abilities can be used to manage roles and restrict access to certain parts of your Application.

Top comments (0)