【问题标题】:Always got "message": "Unauthenticated." - Laravel Passport总是收到“消息”:“未经身份验证。” - Laravel 护照
【发布时间】:2018-09-01 21:19:19
【问题描述】:

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

目前,我可以访问http://localhost/oauth/token,并成功将令牌返回给我。

之后,我正在使用 ARC (Advanced Rest Client) 进行调用我自己的 api 的测试。

我已经传递了诸如

之类的标题
Authorization: Bearer the_token_here
accept: application/json

从那个标头,我只想访问 laravel /user 提供的默认 API。

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

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

我可以按照教程进行登录,但我无法通过端点details 获取数据。它返回{ "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))

【问题讨论】:

  • 路由 /user 中分配了哪些中间件??
  • 参考更新的 'auth:api' @MayankMajithya
  • 路由必须在登录后使用..登录??
  • 请在 kernal.php 中注册这个中间件,然后使用它 'client' => \Laravel\Passport\Http\Middleware\CheckClientCredentials::class,
  • 对你的路由使用“客户端”中间件,它可能会起作用

标签: php laravel laravel-passport


【解决方案1】:

为了得到详细的错误原因信息,你需要去CheckClientCredentials类详情如下

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(不仅在公用文件夹内)

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

官方文档里也有注释refer here

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

【讨论】:

  • 仍然出现错误,我看到了 RewriteCond %{HTTP:Authorization} 。 RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] in .htaccess already
  • @RobertTuanVuit 需要在根文件夹和公用文件夹中
  • 我快疯了,因为身份验证在 local 中运行良好,但在 staging 中却没有,添加 rewrite 规则后它完全有效。但我想更深入地了解为什么它们是必要的,关于它的任何资源或措辞?
  • h3.更新我发现为什么有必要,Apache 和 Passport 中的基本身份验证存在问题,我们没有使用 FastCGI 模块,但无论如何它都会产生噪音。我们使用 php7_module。同样,在调试时,我完全注释了.htaccess 的基本身份验证,但如果没有这些重写行就无法工作。 laravel.com/docs/5.6/authentication#http-basic-authentication
  • CheckClientCredentials 在 laravel 项目中的位置在哪里?
【解决方案2】:

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

php artisan config:cache

【讨论】:

  • 没有。该命令仅清除配置缓存。我的命令清除配置缓存并重新缓存配置。把它们都输入,你就会明白我的意思了。
  • 哦抱歉不知道,以为它只是缓存了它。
  • 当我使用迁移时会发生这种情况吗:回滚???
【解决方案3】:

在 Ubuntu 中,执行以下操作。

启用重写模式。

sudo a2enmod rewrite

转到cd /etc/apache2

然后打开apache2.confnano apache2.conf找到下面一行,将AllowOverride None改为AllowOverride All,如下图。

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

最后重启apache2服务器

sudo service apache2 restart

【讨论】:

    【解决方案4】:

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

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

    【讨论】:

      【解决方案5】:

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

      【讨论】:

        【解决方案6】:

        对于那些收到错误消息 Unauthenticated 即使令牌是正确的, 只需替换 laravel 8 prebuilt routes 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();
        });
        

        【讨论】:

          【解决方案7】:

          万一有人遇到同样的问题,而选择的解决方案没有解决。检查以下内容:

          1) 检查您是否在请求的标头中发送 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中的问题类似

          关于序列化的解释在问题中

          2020 年 1 月 2 日更新

          正如 Zac Grierson 所评论的,供应商文件不应修改,因为它们将在以下内容中发生变化

          作曲家更新

          micksp 找到了更好的解决方案:“将受保护的静态 $serialize = false; 添加到您的 app/Http/Middleware/EncryptCookies.php。然后删除您的浏览器 cookie。"

          【讨论】:

          • 你不应该修改供应商文件,因为它们会随着composer updates而改变。
          • @ZacGrierson 同意,但这个答案确实解决了我的问题,其他人都没有。我现在可以考虑更永久地解决问题
          • 已修复!在同一问题中(答案中的链接):将protected static $serialize = false; 添加到您的应用程序/Http/Middleware/EncryptCookies.php。然后删除您的浏览器 cookie。
          猜你喜欢
          • 2019-06-02
          • 1970-01-01
          • 2017-01-06
          • 2019-02-28
          • 2019-06-14
          • 2017-04-24
          • 2018-02-25
          • 2018-05-02
          • 2019-08-03
          相关资源
          最近更新 更多