With Laravel API you can set abilities or scopes for tokens. In this article we are covering how to set abilities for tokens created using sanctum.
Token abilities always return true if you use first party Sanctum’s SPA authentication It mean using cookie-based a authentication.
Pre setup
First setup a Laravel API using Sanctum. Click here to create a Laravel API authentication using Sanctum. All the example lines are based on the projected created with that article. Make sure to read it before continuing.
Settings Abilities for Sanctum API Tokens
Let learn how to set Abilities or Scopes for API Tokens. You can set abilities for tokens when they are created either in login function or in register function. Depend on the place you decide to create the token. This example is purely based on the example project created above.
Here we are creating the token when a user login with credentials. Therefore we are using login function to set abilities for the token.
//User login with santum token
public function login(Request $request)
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
if (!Auth::attempt($credentials)) {
return response()->json(['message' => 'Invalid login details'], 401);
}
$user = Auth::user();
$token = $user->createToken('auth_token', ['user.view', 'user.edit'])
->plainTextToken;
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
Check Token Abilities within the Controller
Let check token abilities once you done setting abilities. There are two functions available on the logged user objected as
- tokenCan()
- tokenCant()
Use any one of them depend on the scenario to check abilities.
//View user profile information
public function profile(Request $request)
{
if($request->user()->tokenCant('user.view')){
return response()->json(
[
'message'=> "Permssion Denied"
], 403
);
}
return response()->json($request->user());
}
Check Token Abilities using a Middleware
Sanctum has two middleware to check token abilities. They are
- CheckAbilities : Token should has all the listed abilities to pass.
- CheckForAnyAbility: Token should have any listed ability to pass.
First register those two middleware on the Laravel application. Open app.php file on “bootstrap” folder.
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Laravel\Sanctum\Http\Middleware\CheckAbilities;
use Laravel\Sanctum\Http\Middleware\CheckForAnyAbility;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
'abilities' => CheckAbilities::class,
'ability' => CheckForAnyAbility::class,
]);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
Lets set middleware to profile route to passthrough if the token has the abilities of user.view or user.edit
Route::get('/user',[APIAuthenticationController::class,'profile'])
->middleware(['auth:sanctum','ability:user.edit,user.view']);