简体   繁体   中英

Laravel Auth guard [api] is not defined

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

Your auth.php file must be like this :

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM