I have a Laravel 8 project based on auth bootstrap scaffolding. It uses a custom UserProvider that authenticates a user from another source (AWS user pool). The login process works just fine. However, subsequent Ajax calls to a route fail with error 401. Below are are the details.
Server side (config/auth.php)
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'aws',
'model' => App\Models\User::class,
],
]
Providers/AuthServiceProvider.php
public function boot()
{
$this->registerPolicies();
Auth::provider('aws', function ($app, array $config) {
$awsProvider = new AwsUserProvider($app['hash'], $config['model']);
return $awsProvider;
});
}
routes/web.php
Route::get('ict-devices-table', [IctDataController::class, 'getAllDevices']);
Controllers/IctDataController.php
class IctDataController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function getAllDevices()
{
// return json encoded data.
}
}
Client side
As I mentioned, the login is successful, and the user gets redirected to the home page. On that page, the ajax request executes periodically to get the latest data from the 'ict-devices-table' That request returns error 401.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
'url': 'http://localhost:8000/ict-devices-table',
'method': 'GET',
'contentType': 'application/json',
}).done(function (inData) {
//do something useful with the data.
});
The problem is that the controller never executes if auth
middleware gets specified in the constructor. If it is not the getAllDevices
method is called but Auth::check()
returns false and Auth::user()
is null.
However, one clue might be: The custom UserProvider class implements all UserProvider methods, and they get called during login, i.e., validateCredentials
, retrieveById,
etc. However, when the Ajax request gets made, none of those calls appear in the log. Any ideas why this happens and how to fix it?