Yes, Sanctum can be used for authentication in a Laravel application that is API-driven with React frontend and React Native for mobile. Sanctum is a lightweight authentication system that is easy to set up and use. It provides a simple way to authenticate users and issue API tokens.
Sanctum is a good choice for applications that do not require complex authentication requirements. If your application requires more advanced authentication features such as OAuth2, then Passport may be a better choice.
Here is an example of how to use Sanctum for authentication in a Laravel application:
- Install Sanctum using composer:
composer require laravel/sanctum
- Publish the Sanctum configuration file:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
- Run the Sanctum migration:
php artisan migrate
- Add the Sanctum middleware to your API routes:
Route::middleware('auth:sanctum')->group(function () {
// API routes here
});
- To authenticate a user and issue an API token, use the
createTokenmethod:
$user = User::find(1);
$token = $user->createToken('token-name')->plainTextToken;
- To authenticate a user using an API token, send the token in the
Authorizationheader:
Authorization: Bearer {api-token}
For more information on using Sanctum, see the Laravel documentation: https://laravel.com/docs/8.x/sanctum