Laravel 简单验证 API 总是返回未经授权的 401 错误

Laravel Auth simple API always returning Unauthorized 401 error

这让我发疯...一切都应该是正确的,我总是在我的 API 路线中遇到未经授权的错误!!

Api.php 路线:

Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();

});

注册控制器:

    protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'api_token' => Str::random(80),
    ]);
}

数据库:

请求:

接受 application/json 已设置:

我也尝试过使用 jquery 来发出带有查询参数 api_key 的请求,但它也不起作用!!

我找了很多都没有解决这个问题。我有另一个带有 Laravel 和 auth 的新应用程序,它工作得很好,但这个项目很旧,我最近将它更新为 Laravel 7,我不知道为什么它不起作用。

更多信息:

我正在使用 php artisan serve 来为应用程序提供服务。

我的kernel.php:

<?php

命名空间App\Http;

使用Illuminate\Foundation\Http\Kernel作为HttpKernel;

class 内核扩展了 HttpKernel { /** * 应用程序的全局 HTTP 中间件堆栈。 * * 这些中间件在您的应用程序的每个请求期间都是 运行。 * * @var 数组 */ 受保护的$中间件= [ \App\Http\Middleware\TrustProxies::class, \App\Http\Middleware\CheckForMaintenanceMode::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \App\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, ];

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
        'auth:api',
    ],
];

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'language' => \App\Http\Middleware\GetRequestLanguage::class,
    'setLocale' => \App\Http\Middleware\SetLocale::class,
];

/**
 * The priority-sorted list of middleware.
 *
 * This forces non-global middleware to always be in the given order.
 *
 * @var array
 */
protected $middlewarePriority = [
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\Authenticate::class,
    \Illuminate\Routing\Middleware\ThrottleRequests::class,
    \Illuminate\Session\Middleware\AuthenticateSession::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    \Illuminate\Auth\Middleware\Authorize::class,
];

}

谢谢你...我希望你能帮助我...

你只需要像这样在邮递员中将你的令牌作为正文发送 example picture of sending authentication by postman 您必须在正文(表单数据)中发送您的令牌,并且您的令牌密钥必须是 api_token

我找到了解决方案。

当我从 Laravel 6 升级到 7 时,我没有在 auth.php 中更改它:

'hash' => 'false''hash' => false,没有引号...这个废话让我很头疼,最后我发现它导致了问题。

        'api' => [
        'driver' => 'token',
        'provider' => 'users',
        'hash' => false,
    ],

这是因为您没有随请求发送授权令牌。

如果您有令牌,请在请求的 header 中包含授权

axios({method: 'get', url: 'api/user', headers: {
      'Authorization': 'Bearer ' + yourToken,
    }})
    .then((response)=>{ 
      console.log(response.data)
    })

我这样说是因为 api 通常需要额外的步骤才能工作,但如果它在您的 get 参数中工作,那么这就是您所需要的

或者更好的是,默认为所有请求传递它

//js/main.js

axios.defaults.headers.common = {
    'X-CSRF-TOKEN': your_csrfToken,
    'X-Requested-With': 'XMLHttpRequest',
    'Authorization': 'Bearer ' + yourToken,
    
};