简体   繁体   中英

Laravel Passport API Authentication not working with Bearer Token

i'm currently developing a Laravel Application. Inside the Application I need to create a public api, which need to be accessible if a client got an access token.

Therefor i'm using the laravel/passport package.

Retrieving the access_token is working fine. The critical part is to authenticate with this access token and get json data as response from a protected route.

The Setup is the following:

  • Laravel 5.7.6
  • Laravel Passport 6.0.7

With Laravel 5.6.30 and Passport 6.0.7 the cookie serialization got disabled.

/app/Providers/AuthServiceProvider.php

$this->registerPolicies();
Passport::withoutCookieSerialization(); // because of the Laravel Update
Passport::routes();
Passport::tokensExpireIn(Carbon::now()->addDays(20));
Passport::refreshTokensExpireIn(Carbon::now()->addDays(20));

As mentioned over here i changed the expiration time of the tokens so they don't overflow or start with a - .

Over here @adamj mentioned to have a look at the mapApiRoutes()

/app/Providers/RouteServiceProviders.php

protected function mapApiRoutes()
{
    Route::prefix('api')
        ->middleware('auth:api')
        ->namespace($this->namespace)
        ->group(base_path('routes/api.php'));
}

The Request i'm sending towards my API got the following Headers set:

Accept: application/json 
Authorization: Bearer {my_access_token}

The Route i'm trying to access within Postman is the following:

Route::group(['middleware' => ['auth:api']], function () {
  Route::get('/hello/world', function () {
      return 'Hello World';
  });
});

The Response is then always a HTTP Status of 401. Can somebody help?

I really got no more idea on how to fix this.

Thanks in regards!

The error was not inside Laravel. The error was related to Postman.

Inside the Authorization Tab you could choose a type. Unless you don't choose No Auth your manually set Header got replaced by Postman.

Hope this may help anybody.

This is because Apache does not, by default, pass authorization headers to PHP. I found this solution:

https://support.deskpro.com/en/kb/articles/missing-authorization-headers-with-apache

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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