Passport - “Unauthenticated.” - Laravel 5.3

匿名 (未验证) 提交于 2019-12-03 01:25:01

问题:

I hope someone could explain why I'm unauthenticated when already has performed a successfull Oauth 2 authentication process.

I've set up the Passport package like in Laravel's documentation and I successfully get authenticated, receives a token value and so on. But, when I try to do a get request on, let say, /api/user, I get a Unauthenticated error as a response. I use the token value as a header with key name Authorization, just as described in the docs.

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

This function is suppose to give back my self as the authenticated user, but I'm only getting Unauthenticated. Likewise, if I just return the first user, I'm again getting Unauthenticated.

Route::get('/test', function(Request $request) {     return App\User::whereId(1)->first(); })->middleware("auth:api"); 

In a tutorial from Laracast, guiding through the setup of Passport, the guider doesn't have the ->middleware("auth:api") in his routes. But if its not there, well then there's no need for authentication at all!

Please, any suggestions or answers are more then welcome!

回答1:

You have to set an expiration date for the tokens you are generating,

set the boot method in your AuthServiceProvider to something like the code below and try generating a new token. Passports default expiration returns a negative number

public function boot() {   $this->registerPolicies();    Passport::routes();    Passport::tokensExpireIn(Carbon::now()->addDays(15));    Passport::refreshTokensExpireIn(Carbon::now()->addDays(30)); } 


回答2:

Check your user model and the database table, if you have modified the primary id field name to say something other than "id" or even "user_id" you MIGHT run into issues. I debugged an issue regarding modifying the primary id field in my user model and database table to say "acct_id" instead of keeping it as just "id" and the result was "Unauthenticated" When I tried to get the user object via GET /user through the auth:api middleware. Keep in mind I had tried every other fix under the sun until I decided to debug it myself.

ALSO Be sure to UPDATE your passport. As it has had some changes made to it in recent weeks.

I'll link my reference below, it's VERY detailed and well defined as to what I did and how I got to the solution.

Enjoy!

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



回答3:

I had exactly the same error because i forgot to put http before the project name.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!