Home > other >  Laravel Auth guard [api] is not defined
Laravel Auth guard [api] is not defined

Time:07-19

Laravel 8.83.19
Passport 10.4

Simply started a new project and installed passport and want to use middleware for a route but give this error:

Auth guard [api] is not defined

auth.php

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    ],
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
        'hash' => false,
    ],

AuthServiceProvider.php

 public function boot()
    {
Passport::routes();
}

User Model

use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
...

User Controller

class UserController extends Controller
{
    public function index(Request $request)
    {
        return User::all();
    }

Api.php

Route::middleware('auth:api')->group(function () {
    Route::get('/user/index', [UserController::class, 'index']);
});

But when I run http://localhost:8000/api/user/index give me:

InvalidArgumentException: Auth guard [api] is not defined. in file D:\Workshop\Other\xxx\xxxapi\vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php on line 84

ofcourse I cleared cache:

Route::get('/clear', function() {

    Artisan::call('cache:clear');
    Artisan::call('config:clear');
    Artisan::call('config:cache');
    Artisan::call('view:clear');
    Artisan::call('route:cache');

    return "Cleared!";
});

By run this:

http://localhost:8000/clear

CodePudding user response:

Your auth.php file must be like this :

<?php
'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
            'hash' => false,
            ]
    ]
?>

CodePudding user response:

You need to clear config cache to take effect. for Unauthenticated it means token is not valid or is not passed correctly

https://laravel.com/docs/5.7/passport#passing-the-access-token

CodePudding user response:

try this solve

step 1

php artisan optimize
php artisan migrate

step 2

php artisan passport:keys

in .env file define two variables

PASSPORT_PRIVATE_KEY= ( get value from "storage/oauth-private.key" )
PASSPORT_PUBLIC_KEY= ( get value from "storage/oauth-public.key" )

step 3

php artisan passport:client
php artisan optimize
  • Related