An API is stateless. Are you using sanctum, passport, or other?
Laravel API Multi-guard
Hello, I'm trying to create an API that is going to be used in both web and mobile apps. I can't find where is the problem when I try to login as a player for example. After finishing part of the logic and I tested the login route it worked and then I tried a auth:player specific route and It worked. The next day when I tried it didn't work anymore so I assume is a session problem.
AccountType.php (Enum) - it contains a lot of function related to guards info and others
case PLAYER = 'player';
case ADMIN = 'admin';
case HOST = 'host';
/**
* @param StatefulGuard $guard
* @return AccountType|null
* @throws ReflectionException
*/
public static function fromGuard(StatefulGuard $guard): ?AccountType
{
$class = new \ReflectionClass($guard);
return self::fromGuardName($class->getProperty('name')->getValue($guard));
}
api.php
foreach (AccountType::cases() as $accountType) {
$guard = $accountType->guardName();
Route::group([
'middleware' => [
'auth:' . $guard,
'ensure-account-type:' . $guard,
],
'prefix' => $guard,
'as' => $guard . '.',
], base_path('routes/api/' . $guard . '.php'));
}
Each 3 guards have models that extend the User model with the Authenticatable
auth.php - config
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'player' => [
'driver' => 'session',
'provider' => 'players',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'host' => [
'driver' => 'session',
'provider' => 'hosts',
],
],
$type->guard()->login($user, $this->boolean('remember'));
This part of the login does not seem to work. After the whole login when I try to check for the Auth it is always displaying false. Any ideas what could be wrong? I tried to set the session to file or database but still does not work. I can share more info if necessary. I am going to use roles like recommended in other posts if I can't make this work.
Thank you for your time!
@tofware As @jlrdw says, an API is typically stateless, so you shouldn’t be using token-based authentication instead of session-based authentication.
In addition, a user is a user. Please use roles to determine what a user can and cannot do instead of creating multiple user models, migrations, controllers, guards, etc.
Please or to participate in this conversation.