Sanctum is an easy package to issue API tokens to the users without the complication of OAuth. Sanctum provides authentication services based on Laravel built-in cookie base sessions. For small applications, I prefer using Sanctum because it’s simple and easy.
Laravel Sanctum gives a lightweight authentication system for simple token based APIs and mobile applications, and single page applications (SPA). In Sanctum, we have two different ways mainly as mentioned below:
1) The API Token Authentication.
2) Single page application authentication.
This Authentication process is similar to API token Authentication process.
It uses a token that you must issue before you send a request to the server. You get a token via login or register routes, then you must include this token in the Authorization token as bearer token every next request.
This authentication process does not need tokens. Instead of this, it uses laravel integrated cookie base session auth services. When we use this process of authentication, we do not include a bearer token on every request. It is used when you build first-party SPA, for your front-end project in your Laravel project or any other different project for that matter.
You can check out the codes used to create a Rest API for Laravel application below:
composer create-project laravel/laravel –prefer-dist laravel-sanctum
composer require laravel/sanctum
php artisan vendor:publish --
provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
}
Routing is one of the important features of a Laravel application. In this part, we will set up our API routes:use App\Http\Controllers\AuthenticationController;
Route::post('/register', [AuthenticationController::class, 'createAccount']);
Php artisan make: controller AuthenticationController
class AuthenticationController extends Controller
{
public function createAccount(Request $request)
{
$attr = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|unique:users,email',
'password' => 'required|string|min:6|confirmed'
]);
$user = User::create([
'name' => $attr['name'],
'password' => bcrypt($attr['password']),
'email' => $attr['email']
]);
return $this->success([
'token' => $user->createToken('tokens')->plainTextToken
]);
}
I have written a logic in the Controller above. The createAccount() method creates new validated users that generates tokens if successfully registered.
Conclusion:
In this blog, we tried explaining to you what Laravel sanctum is and how it works. We have elaborated a step-by-step procedure on how to authenticate and give access to users using Laravel sanctum.
By using this, you can authenticate faster and easier than any other library.