Problem with Custom Guard and Middleware in Laravel Passport
Laravel Version: 9.26.1
Passport Version: 10.4.2
I'm facing an issue with my custom guard and middleware setup using Laravel Passport. My middleware always returns false for authentication. Here are the details of my configuration:
Config/auth.php:
'guards' => [
'channel_partner' => [
'driver' => 'passport',
'provider' => 'channel_partners',
],
],
'providers' => [
'channel_partners' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
],
App\Providers\AuthServiceProvider.php:
public function boot()
{
$this->registerPolicies();
Passport::routes();
Passport::tokensExpireIn(Carbon::now()->addHours(24));
Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
}
routes/api.php:
Route::apiResource('country', 'CountryListController', ['only' => ['index'], 'as' => 'country'])->middleware('channel_partner_auth');
App\Http\Middleware\ChannelPartnerAuth.php:
public function handle($request, Closure $next)
{
if (!Auth::guard('channel_partner')->check()) {
return response()->json(["status" => "Error", 'message' => 'Unauthorized'], 401);
}
return $next($request);
}
Login Code:
$response = Http::asForm()->post($appUrl . '/oauth/token', array_merge([
'grant_type' => $grantType,
'client_id' => $this->client->id,
'client_secret' => $this->client->secret,
'scope' => '',
], $params));
if ($response->successful()) {
$data = $response->json();
$responseArray = [
'status' => 'Success',
'data' => [
'token' => $data['access_token'],
'refreshToken' => $data['refresh_token'],
"tokenExpiry" => $tokenExpiryDate,
"refrshTokenExpiry" => $refrshTokenExpiryDate
]
];
return response()->json($responseArray, 200);
}
In the User model, I've added:
The login code returns a valid access and refresh token. When debugging, I see that the request has the expected headers. Additionally, I'm able to authenticate the request by adding an additional check after decoding the token.
Despite this,Auth::guard('channel_partner')->check()always returns false in my middleware.
Any advice on what I might be missing or what to check next?