总是收到“消息”:“未经身份验证”。-Laravel护照

Kas*_*ady 5 php laravel laravel-passport

我整天都在找很多教程。我的设置与所有基本教程完全相同。

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

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

我已经传递了诸如

Authorization: Bearer the_token_here
accept: application/json
Run Code Online (Sandbox Code Playgroud)

从该标头中,我只想访问laravel提供的默认API /user

但是,我总是得到回应 { "message": "Unauthenticated." }

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

我可以按照教程进行登录,但是无法通过Endpoint获取数据details。返回响应{ "message": "Unauthenticated." }

我的路线 api.php

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

顺便说一句,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))
Run Code Online (Sandbox Code Playgroud)

Kas*_*ady 23

为了获得原因的详细错误消息,您需要转到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);
}
Run Code Online (Sandbox Code Playgroud)

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

解决方案是将此添加到.htaccess根文件夹中(不仅在公用文件夹内)

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Run Code Online (Sandbox Code Playgroud)

官方文档中还有一个注释请参考这里

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


Sav*_*lon 6

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

php artisan config:cache