使用个人访问令牌在 Postman 中未经身份验证的 Laravel 5.3 Passport API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39833897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:32:52  来源:igfitidea点击:

Laravel 5.3 Passport API unauthenticated in Postman using personal access tokens

phplaravellaravel-5.3

提问by twigg

I have set-up Laravel using passport as per the documentation here: https://laravel.com/docs/5.3/passport

我已经按照这里的文档使用护照设置了 Laravel:https://laravel.com/docs/5.3/passport

A few people have asked about this using the oAuth implementation but I'm trying to use the personal access tokens not oAuth. One suggestion was to remove the auth middleware but obviously this leaves the application wide open so anyone can make requests.

一些人使用 oAuth 实现询问了这个问题,但我正在尝试使用个人访问令牌而不是 oAuth。一个建议是删除 auth 中间件,但显然这会使应用程序完全开放,因此任何人都可以提出请求。

I have the following route (in routes/api.php):

我有以下路线(在 routes/api.php 中):

Route::get('/test', function(){
    return 'returned string from test route';
})->middleware('auth:api');

This works if I remove the auth middleware so the route is working correctly but when enabling the auth middleware again I get the following error in postman:

如果我删除 auth 中间件,这会起作用,因此路由可以正常工作,但是当再次启用 auth 中间件时,我在邮递员中收到以下错误:

{"error":"Unauthenticated."}

These are the headers being sent via postman:

这些是通过邮递员发送的标头:

GET /api/test HTTP/1.1
Host: localhost:8000
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImU4ZmY5MDMwY2EyM2E2MDYwODViN2Y3ZWNiMzcxNDY1MzQxNDViNTk4ODU4NmZhNDljYzU2YjMzYWZiNzhkYTk5OTIwZWMzYzEwNTBkNjZjIn0.eyJhdWQiOiIyIiwianRpIjoiZThmZjkwMzBjYTIzYTYwNjA4NWI3ZjdlY2IzNzE0NjUzNDE0NWI1OTg4NTg2ZmE0OWNjNTZiMzNhZmI3OGRhOTk5MjBlYzNjMTA1MGQ2NmMiLCJpYXQiOjE0NzU1MDMxNjUsIm5iZiI6MTQ3NTUwMzE2NSwiZXhwIjowLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.IpzKK29dJCpliUXQvPRss87kGFngFcXXwV3jRwhbZOZLxl-4UV70cBsSigmqUuBsHQ4onVl_Cjcq6cEmMFvTZZr7D9AtY3EmScvMPjoFh4KQ3wgd5CoyWfcLQgoBxbElNxL0xW2fIQhpeQd_8Yz_Pr5BByGVTpxfg4JJZ4PzovvZsa2R3izYtqw6-qeurQOtsfOnot5uoLDeDDc76klifnfHfOcNZSoIFGNP3gIGKYBe6lfFuDViR_mQkwQS5_UmERt3GSkEvJjGMtwcRjWY7VPAJ4tvWLnyLw0roGU2e37L0wsqfJ8OrG0Cipv-anXAW_utSo-fiVMr8ZeAWIPguq73Zd44x95YY3nNPOKD5dVIRZM7rQgdhjIwTEz1ggtSXLp-Fu3QOtXaHUahCHvjOTdiTYEa-GR4TZ5wGzt-aRhjdBB7WTe0C6T9ZWVwQr0kJk8AxW6ne87wwJYp_shGunTclZ3SCq5VYg2K_MclbJl65-dT8x-nwqg0lqfNx9s1wmtryrMFIPoBEyaGNEK1aWGHKq418-BIQ1_UAhcHHtEXclWvsGWwhyo3aso-E-sCN2o_IkYvSboIsdFAIXvDvQmoAwis6f1J57zWH8AW1ynCFcBgzBDjIyiaCE5nqtb_4zbEXr8L1EbcllbtZkq3vd9w996kO7xlpBEWwPY8IWg
Accept: application/json
Cache-Control: no-cache
Postman-Token: 6bc483b2-23df-acce-7eef-5a443f8f5d45

回答by Andre F.

  • Firstly, NEVERmodify the vendor files unless you have a fully legitimate reason for doing so and there's a feature you wish to see implemented or a bug you've discovered and fixed in the package you're using.

  • Expiration time on the JWT might be already set to expire as soon as it's made. Here's a link you can use to check the "ttl" (Time To Live) field of your access tokens:

  • 首先,永远不要修改供应商文件,除非您有完全合法的理由这样做,并且您希望看到实现的功能或您在正在使用的包中发现并修复的错误。

  • JWT 上的过期时间可能已经设置为在创建后立即过期。这是一个链接,您可以用来检查访问令牌的“ttl”(生存时间)字段:

https://jwt.io/

https://jwt.io/

If you find that your tokens are expiring on creation, you can go to your app\providers\AuthServiceProvider.phpclass and add in these methods on use of Passport Class:

如果您发现您的令牌在创建时过期,您可以转到您的app\providers\AuthServiceProvider.php类并在使用 Passport 类时添加这些方法:

use Carbon\Carbon;
use Laravel\Passport\Passport;
...

Class AuthServiceProvider extends ServiceProvider {
    ...
    ...

    public function boot() {
        $this->registerPolicies();
        Passport::routes();
        Passport::tokensExpireIn(Carbon::now()->addYears(20));//You can also use addDays(10)
        Passport::refreshTokensExpireIn(Carbon::now()->addYears(20));//You can also use addDays(10) 
        Passport::pruneRevokedTokens(); //basic garbage collector
    }
}
  • Make sure you're using the most recent version of Passport Currently I'm on version 1.0.8 but I might already be out of date as they and the community are constantly pushing new revisions every few weeks.
  • 确保您使用的是最新版本的 Passport 目前我使用的是 1.0.8 版,但我可能已经过时了,因为他们和社区每隔几周就会不断推出新的修订版。

Here are links to some related issues regarding this problem. You might be able to locate your answer within one of the below links. If what's mentioned above isn't what you're looking for.

以下是有关此问题的一些相关问题的链接。您或许可以在以下链接之一中找到您的答案。如果上面提到的不是你要找的。

Passport - "Unauthenticated." - Laravel 5.3

护照 - “未经认证”。- Laravel 5.3

Very Detailed

非常详细

https://github.com/laravel/passport/issues/151

https://github.com/laravel/passport/issues/151

回答by Jason Llamorin

Please check if the token was copied properly, i always observed when i copy the personal tokens, in the last there is a word 'Close' copied also. eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImU4ZmY5MDMwY2EyM2E2MDYwODViN2Y3ZWNiMzcxNDY1MzQxNDViNTk4ODU4NmZhNDljYzU2YjMzYWZiNzhkYTk5OTIwZWMzYzEwNTBkNjZjIn0.eyJhdWQiOiIyIiwianRpIjoiZThmZjkwMzBjYTIzYTYwNjA4NWI3ZjdlY2IzNzE0NjUzNDE0NWI1OTg4NTg2ZmE0OWNjNTZiMzNhZmI3OGRhOTk5MjBlYzNjMTA1MGQ2NmMiLCJpYXQiOjE0NzU1MDMxNjUsIm5iZiI6MTQ3NTUwMzE2NSwiZXhwIjowLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.IpzKK29dJCpliUXQvPRss87kGFngFcXXwV3jRwhbZOZLxl-4UV70cBsSigmqUuBsHQ4onVl_Cjcq6cEmMFvTZZr7D9AtY3EmScvMPjoFh4KQ3wgd5CoyWfcLQgoBxbElNxL0xW2fIQhpeQd_8Yz_Pr5BByGVTpxfg4JJZ4PzovvZsa2R3izYtqw6-qeurQOtsfOnot5uoLDeDDc76klifnfHfOcNZSoIFGNP3gIGKYBe6lfFuDViR_mQkwQS5_UmERt3GSkEvJjGMtwcRjWY7VPAJ4tvWLnyLw0roGU2e37L0wsqfJ8OrG0Cipv-anXAW_utSo-fiVMr8ZeAWIPguq73Zd44x95YY3nNPOKD5dVIRZM7rQgdhjIwTEz1ggtSXLp-Fu3QOtXaHUahCHvjOTdiTYEa-GR4TZ5wGzt-aRhjdBB7WTe0C6T9ZWVwQr0kJk8AxW6ne87wwJYp_shGunTclZ3SCq5VYg2K_MclbJl65-dT8x-nwqg0lqfNx9s1wmtryrMFIPoBEyaGNEK1aWGHKq418-BIQ1_UAhcHHtEXclWvsGWwhyo3aso-E-sCN2o_IkYvSboIsdFAIXvDvQmoAwis6f1J57zWH8AW1ynCFcBgzBDjIyiaCE5nqtb_4zbEXr8L1EbcllbtZkq3vd9w996kO7xlpBEWwPY8IWg Copy

请检查令牌是否正确复制,我在复制个人令牌时总是观察到,最后也复制了一个词“关闭”。 eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImU4ZmY5MDMwY2EyM2E2MDYwODViN2Y3ZWNiMzcxNDY1MzQxNDViNTk4ODU4NmZhNDljYzU2YjMzYWZiNzhkYTk5OTIwZWMzYzEwNTBkNjZjIn0.eyJhdWQiOiIyIiwianRpIjoiZThmZjkwMzBjYTIzYTYwNjA4NWI3ZjdlY2IzNzE0NjUzNDE0NWI1OTg4NTg2ZmE0OWNjNTZiMzNhZmI3OGRhOTk5MjBlYzNjMTA1MGQ2NmMiLCJpYXQiOjE0NzU1MDMxNjUsIm5iZiI6MTQ3NTUwMzE2NSwiZXhwIjowLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.IpzKK29dJCpliUXQvPRss87kGFngFcXXwV3jRwhbZOZLxl-4UV70cBsSigmqUuBsHQ4onVl_Cjcq6cEmMFvTZZr7D9AtY3EmScvMPjoFh4KQ3wgd5CoyWfcLQgoBxbElNxL0xW2fIQhpeQd_8Yz_Pr5BByGVTpxfg4JJZ4PzovvZsa2R3izYtqw6-qeurQOtsfOnot5uoLDeDDc76klifnfHfOcNZSoIFGNP3gIGKYBe6lfFuDViR_mQkwQS5_UmERt3GSkEvJjGMtwcRjWY7VPAJ4tvWLnyLw0roGU2e37L0wsqfJ8OrG0Cipv-anXAW_utSo-fiVMr8ZeAWIPguq73Zd44x95YY3nNPOKD5dVIRZM7rQgdhjIwTEz1ggtSXLp-Fu3QOtXaHUahCHvjOTdiTYEa-GR4TZ5wGzt-aRhjdBB7WTe0C6T9ZWVwQr0kJk8AxW6ne87wwJYp_shGunTclZ3SCq5VYg2K_MclbJl65-dT8x-nwqg0lqfNx9s1wmtryrMFIPoBEyaGNEK1aWGHKq418-BIQ1_UAhcHHtEXclWvsGWwhyo3aso-E-sCN2o_IkYvSboIsdFAIXvDvQmoAwis6f1J57zWH8AW1ynCFcBgzBDjIyiaCE5nqtb_4zbEXr8L1EbcllbtZkq3vd9w996kO7xlpBEWwPY8IWg Copy

If this is not your case check if that token exist, or generate a new one. you can use this format to protect route like this

如果这不是您的情况,请检查该令牌是否存在,或生成一个新令牌。您可以使用这种格式来保护这样的路线

Route::middleware('auth:api')->get('/home', function(){
    return 'test';
});

回答by maturecheese

I Had this problem ... two hours down the pan. Something very strange was happening and in my case I think Postman was the culprit.

我遇到了这个问题......在平底锅下两个小时。发生了一些非常奇怪的事情,就我而言,我认为 Postman 是罪魁祸首。

Inspect the received header to rule it out:

检查接收到的标头以排除它:

Route::get('/test', function(){
    dd( Request::header());
})/*->middleware('auth:api')*/; //disable auth middleware to inspect header

this is the strange thing I found:

这是我发现的奇怪的事情:

.........
"authorization" => array:1 [
    0 => b"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJ ................

what the hell was the 'b' before Bearer ACCESS_TOKEN??? I typed it out again and it dissapeared and auth middleware started working.

Bearer之前的'b'到底是什么ACCESS_TOKEN???我再次输入它,它消失了,身份验证中间件开始工作。

Inspect the header exactly and then add the middleware back. This might just be the cause!

准确检查标题,然后添加中间件。这可能只是原因!

回答by baxri

in passport.php there are two functions

在passport.php中有两个功能

public static function tokensExpireIn(DateTimeInterface $date = null)
{
    if (is_null($date)) {
        return static::$tokensExpireAt
                        ? Carbon::now()->diff(static::$tokensExpireAt)
                        : new DateInterval('P100Y');
    } else {
        static::$tokensExpireAt = $date;
    }

    return new static;
}

/**
 * Get or set when refresh tokens expire.
 *
 * @param  \DateTimeInterface|null  $date
 * @return \DateInterval|static
 */
public static function refreshTokensExpireIn(DateTimeInterface $date = null)
{
    if (is_null($date)) {
        return static::$refreshTokensExpireAt
                        ? Carbon::now()->diff(static::$refreshTokensExpireAt)
                        : new DateInterval('P100Y');
    } else {
        static::$refreshTokensExpireAt = $date;
    }

    return new static;
}

you must change P100Y to P1Y. and also in PassportserviceProvider.php at line 101 there is code

您必须将 P100Y 更改为 P1Y。并且在 PassportserviceProvider.php 的第 101 行也有代码

 $server->enableGrantType(
                new PersonalAccessGrant, new DateInterval('P100Y')
            );

change P100Y to P1Y. hope it helps you :)

将 P100Y 更改为 P1Y。希望对你有帮助:)