How do I fix the “401 Unauthorized” error with Laravel 8 Sanctum?

Viewed 584

I am trying to build an API using Laravel 8 and Sanctum Authentication. I know that they are many similar questions but still haven't found any working solution.

In my situation I don't use Vue or Angular, I give directly the auth token to the users and they need to call the API endpoints to get the data.

Here is my routes/api.php:

Route::group(['middleware' => ['auth:sanctum'], 'as' => 'api.'], function () {
    Route::get('polls/random', [PollController::class, 'random'])->name('polls.random');
    Route::get('polls/vote', [PollController::class, 'vote'])->name('polls.vote');
});

Route::fallback(function() {
    throw new PageNotFoundException();
});

config/cors.php

'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,

config/sanctum.php

'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
    '%s%s',
    'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
    env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),

On localhost I am using virtual hosts, so here is my .env file:

SANCTUM_STATEFUL_DOMAINS=beteu,domain.com

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

Here is how I try to call the API:

$client = new Client(['base_uri' => $this->api_url]);
$access_token = $this->api_token;

$headers = [
    'Authorization' => 'Bearer '.$access_token,
    'Accept'        => 'application/json',
];

try {
    $response = $client->request('GET', $this->path, [
        'headers' => $headers
    ]);
}
catch (\Exception $exception) {
    echo $exception->getMessage();
    \Log::info($exception->getMessage());
    exit();
}

I have tried a lot of the possible solutions here but always get the 401 Unauthenticated Error.

Much appreciate your help!

0 Answers
Related