总有 "message": "Unauthenticated." - Laravel 护照

Always got "message": "Unauthenticated." - Laravel Passport

这一整天我找到了很多教程。我的设置与那里的所有基本教程完全相同。

目前,我可以使用 return 令牌成功访问 http://localhost/oauth/token

在那之后,我正在使用 ARC(高级 Rest 客户端)来测试调用我自己的 api。

我通过了header例如

Authorization: Bearer the_token_here
accept: application/json

从 header 开始,我只想访问 laravel /user.

提供的默认值 API

但是,我总是收到 { "message": "Unauthenticated." }

的回复

参考本教程https://itsolutionstuff.com/post/laravel-5-how-to-create-api-authentication-using-passport-example.html

我可以按照教程进行登录,但无法通过端点 details 获取数据。它 returning { "message": "Unauthenticated." }

的响应

我的路线api.php

Route::group(['prefix' => 'v1', 'middleware' => 'auth:api'], function(){
    Route::get('/user', function( Request $request ){
        return $request->user();
    });
});

顺便说一下,laravel.log 中没有错误消息,我已设置为调试模式

更新感谢 Mayank

的评论指出
League\OAuth2\Server\Exception\OAuthServerException: The resource owner or authorization server denied the request. in /.../vendor/league/oauth2-server/src/Exception/OAuthServerException.php:173
Stack trace:
#0 /.../vendor/league/oauth2-server/src/AuthorizationValidators/BearerTokenValidator.php(59): League\OAuth2\Server\Exception\OAuthServerException::accessDenied('Missing "Author...')
#1 /.../vendor/league/oauth2-server/src/ResourceServer.php(82): League\OAuth2\Server\AuthorizationValidators\BearerTokenValidator->validateAuthorization(Object(Zend\Diactoros\ServerRequest))
#2 /.../vendor/laravel/passport/src/Http/Middleware/CheckClientCredentials.php(46): League\OAuth2\Server\ResourceServer->validateAuthenticatedRequest(Object(Zend\Diactoros\ServerRequest))

为了获得原因的详细错误消息,您需要转到CheckClientCredentials class 详情如下

public function handle($request, Closure $next, ...$scopes)
{
    $psr = (new DiactorosFactory)->createRequest($request);

    try {
        $psr = $this->server->validateAuthenticatedRequest($psr);
    } catch (OAuthServerException $e) {
        error_log($e->getHint()); // add this line to know the actual error
        throw new AuthenticationException;
    }

    $this->validateScopes($psr, $scopes);

    return $next($request);
}

根据错误信息。在我的问题中。

解决方案是将其添加到根文件夹的 .htaccess(不仅在 public 文件夹内)

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

官方文档中也有说明refer here

如果没有上述配置,Authorization header 将在从任何地方调用应用程序时被忽略。一旦被忽略,class 内部将无法检索此 header 数据

以防大家有同样的问题,而选择的方案没有解决。检查以下内容:

1) 检查您是否在请求的 header 中发送了 X-CSRF-TOKEN。在我的例子中,我将 vue 与 axios 结合使用:

let token = window.$('meta[name="csrf-token"]').attr('content');
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token;

如果要发送,请尝试更改 vendor/laravel/passport/src/Passport 中的以下值。php 第 125 行(可能会更改)

正确错误

public static $unserializesCookies = false;

问题可能与https://github.com/laravel/passport/issues/452

中的问题类似

issue中有关于序列化的解释

2020 年 1 月 2 日更新

正如 Zac Grierson 评论的那样,不应修改供应商文件,因为它们将在以下内容中更改

composer update

micksp 找到了更好的 解决方案: "add protected static $serialize = false; to your app/Http/Middleware/EncryptCookies.php。然后删除浏览器 cookie。"

如果您尝试了所有方法但似乎没有任何效果,请尝试清除您的配置缓存。我花了两天时间重新安装 passport,学习了 10 亿个教程,创建了测试项目等等,最终意识到我需要清除缓存

php artisan config:cache

将以下代码粘贴到项目根文件夹中的 .htaccess 文件中。

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1

在 Ubuntu 中,执​​行以下操作。

启用重写模式。

sudo a2enmod rewrite

转到cd /etc/apache2

然后打开apache2.confnano apache2.conf找到下面这一行,改AllowOverrideNoneAllowOverride All,如下所示。

# /etc/apache2/apache2.conf
<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

最后,重启apache2服务器

sudo service apache2 restart

我在使用 Laravel 8 + Postman 时遇到了同样的问题,我在数据库中将密码加密到 Bcypt(默认 laravel 加密用户模型的密码)。我正在解决问题。

对于那些收到错误消息未验证的人,即使令牌是正确的, 只需替换 laravel 8 预建路由 api:

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

进入

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