Yes, Sanctum supports both user-based tokens and client-based tokens at the same time.
To achieve this, you can use Sanctum's ability to issue multiple token types. By default, Sanctum issues tokens for authenticated users, but you can also configure it to issue tokens for clients.
Here's how you can set it up:
- Install Sanctum if you haven't already:
composer require laravel/sanctum
- Publish the Sanctum configuration file:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
-
In the
config/sanctum.phpconfiguration file, make sure thestatefuloption is set totrue. This allows Sanctum to issue tokens for both authenticated users and clients. -
In your
AuthServiceProvider, add theSanctum::usePersonalAccessTokenModel()method call to thebootmethod. This ensures that Sanctum uses the correct token model for both user and client tokens:
use Laravel\Sanctum\Sanctum;
public function boot()
{
$this->registerPolicies();
Sanctum::usePersonalAccessTokenModel(ClientToken::class);
}
- Create a new model for client tokens. This model should extend the
Laravel\Sanctum\PersonalAccessTokenclass:
use Laravel\Sanctum\PersonalAccessToken;
class ClientToken extends PersonalAccessToken
{
// Add any additional logic or customization you need for client tokens
}
- In your authentication logic, when a user logs in, you can generate a user token using Sanctum's
createTokenmethod:
use Illuminate\Support\Facades\Auth;
$user = Auth::user();
$token = $user->createToken('user-token')->plainTextToken;
- For client-based tokens, you can generate a token using the
createTokenmethod on theClientTokenmodel:
use App\Models\ClientToken;
$clientToken = ClientToken::create([
'tokenable_id' => null, // Set to null for client tokens
'name' => 'client-token',
'token' => 'your-client-token', // Generate a unique token for each client
]);
Now, you can use the generated tokens for authentication. User tokens can be used for authenticated user endpoints, while client tokens can be used for the inventory endpoint that is accessible to guests.
Remember to handle token authentication in your API routes using Sanctum's middleware.
I hope this helps! Let me know if you have any further questions.