简体   繁体   English

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

[英]Always got "message": "Unauthenticated." - Laravel Passport

I had find many tutorial this whole day.我这一整天都找到了很多教程。 And my setup is exactly the same as all the basic tutorial out there.我的设置与那里的所有基本教程完全相同。

Currently, i'm able to access http://localhost/oauth/token with successfully return token to me.目前,我能够访问http://localhost/oauth/token并成功返回令牌给我。

After that, i'm using ARC (Advanced Rest Client) to do the testing of calling my own api.之后,我使用 ARC(高级 Rest 客户端)来测试调用我自己的 api。

I had passed header such as我已经通过了 header 比如

Authorization: Bearer the_token_here
accept: application/json

From that header, I just wanted to access the default API provided by laravel /user .从那个 header,我只想访问 laravel /user提供的默认 API。

But, I always got response of { "message": "Unauthenticated." }但是,我总是收到{ "message": "Unauthenticated." } { "message": "Unauthenticated." }

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

I'm able to do login as per tutorial, but i'm unable to get data by endpoint details .我可以按照教程进行登录,但无法通过端点details获取数据。 It returning response of { "message": "Unauthenticated." }它返回{ "message": "Unauthenticated." } { "message": "Unauthenticated." }

My route of api.php我的路由api.php

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

By the way, there are no error message in laravel.log and i had set to Debug mode顺便说一句,laravel.log 中没有错误消息,我已设置为调试模式

UPDATE Thanks to Comment point out by Mayank更新感谢 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))

In order to get detail error message of the causes, you need to go to CheckClientCredentials class detail as below为了获得原因的详细错误消息,您需要转到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);
}

Based on the error message.根据错误信息。 in my question.在我的问题中。

The solution is adding this to .htaccess of root folder (not only inside the public folder)解决方案是将其添加到根文件夹的.htaccess中(不仅在公用文件夹内)

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

There's also a note in the official documents refer here官方文档中还有一个注释请参考这里

Without above configuration, the Authorization header will be ignored during call from anywhere to app.如果没有以上配置,在从任何地方调用应用程序时, Authorization标头将被忽略。 Once ignored, inside class will unable to retrieve this header data一旦忽略,内部类将无法检索此标头数据

In the event you've tried everything and nothing seems to work, try clearing your configuration cache.如果您尝试了所有方法但似乎没有任何效果,请尝试清除配置缓存。 I spent two days reinstalling passport, following a billion tutorials, creating test projects etc. all to eventually realise I needed to clear my cache我花了两天时间重新安装通行证,遵循十亿个教程,创建测试项目等,最终意识到我需要清除缓存

php artisan config:cache

In Ubuntu, do the following.在 Ubuntu 中,执行以下操作。

Enable the rewrite mode.启用重写模式。

sudo a2enmod rewrite

Go to cd /etc/apache2转到cd /etc/apache2

Then open apache2.conf nano apache2.conf and find out the following line and change AllowOverride None to AllowOverride All as shown below.然后打开apache2.conf nano apache2.conf并找到以下行并将AllowOverride None更改为AllowOverride All ,如下所示。

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

Finally, restart apache2 server最后重启apache2服务器

sudo service apache2 restart

Paste below code in .htaccess file in your project root folder.将以下代码粘贴到项目根文件夹中的 .htaccess 文件中。

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

I had same problem with Laravel 8 + Postman and I was encrypt password in Database to Bcypt (default laravel encrypt for password of Users model).我在 Laravel 8 + Postman 上遇到了同样的问题,我将数据库中的密码加密到 Bcypt(用户模型密码的默认 Laravel 加密)。 I was resolve the problem.我正在解决问题。

图 1图 2

For those getting error message Unauthenticated even if the token is correct, just replace laravel 8 prebuilt routes api:对于那些收到错误消息 Unauthenticated 即使令牌是正确的,只需替换 laravel 8 prebuilt routes api:

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

into进入

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

In case anyone has the same problem, and the selected solution do not solve it.万一有人遇到同样的问题,并且选择的解决方案没有解决它。 Check the following:检查以下内容:

1) Check you are sending the X-CSRF-TOKEN in the header of the request. 1) 检查您是否在请求的标头中发送 X-CSRF-TOKEN。 In my case iḿ using vue with axios:在我的情况下,iḿ 使用 vue 和 axios:

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

If you are sending it, try changing the following value in vendor/laravel/passport/src/Passport.php line 125 (may change)如果您要发送它,请尝试更改vendor/laravel/passport/src/Passport.php第 125 行中的以下值(可能会更改)

From True to False

public static $unserializesCookies = false;

The issue may be similar to the one in https://github.com/laravel/passport/issues/452该问题可能与https://github.com/laravel/passport/issues/452 中的问题类似

An explanation about serialization is in the issue关于序列化的解释在问题中

UPDATE 01/02/2020更新 01/02/2020

As Zac Grierson commented, vendors files should not be modified as they will change in the following正如Zac Grierson评论的那样,不应修改供应商文件,因为它们将在以下内容中发生变化

composer update作曲家更新

micksp found a better solution : " add protected static $serialize = false; to your app/Http/Middleware/EncryptCookies.php. Then remove your browser cookies. " micksp找到了一个更好的解决方案:“将 protected static $serialize = false; 添加到您的 app/Http/Middleware/EncryptCookies.php。然后删除您的浏览器 cookie。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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