简体   繁体   中英

Laravel Passport API call always return Unauthenticated

So I have setup my API with Passport and tried to make GET request for almost a week now but still getting the response bellow :

{
"message": "Unauthenticated."
}

Below are my configuration :

Auth.php

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

'guards' => [
    'web' => [
        'driver' => 'token',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
        //'hash' => true,
    ],
],

AuthServiceProvider.php

public function boot()
{
    $this->registerPolicies();

    //
    Passport::routes();
    Passport::tokensExpireIn(Carbon::now()->addDays(7));

   Passport::refreshTokensExpireIn(Carbon::now()->addDays(14));



}

RouteServiceProvider

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

Controller : Token request function using user credentials as per laravel doc

public function callback(Request $request)
{
     $http = new Client();
    $token_url=url('oauth/token');

$response = $http->post($token_url, [
    'form_params' => [
        'grant_type' => 'password',
        'client_id' => $this->client_id,
        'client_secret' => $this->client_secret,
        'username'=>'my-username',
        'password'=>'my-password',
        'scope' =>'*',
    ],
]);

return json_decode((string) $response->getBody(), true);
}

Which returns an access_token that I use in my request in my request . I tried all the solution listed below and none of them worked :

.htaccess

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

Passport.php line 167

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

    static::$tokensExpireAt = $date;

    return new static;
}

Please help , I'm desperate now :)

The problem is how you authenticate and which token you are using.

There are 2 ways to generate token

  1. Users login and you use create token to get the token if user is authenticated.
  2. Generate a client and use PRE built routes by passport to get token

Now in the API routes you have to tell in your method how you are authenticating for example

// Below one is for authenticating Client token  
Route::get('/test', 'Api\TestController@index')->middleware('client_credentials');
// Below one is for the User token  
Route::get('/test', 'Api\TestController@index')->middleware('auth:api');

And Remember if you are using client authentication, you have to add the below line in routemiddleware in App/http/kernel.php

'client_credentials' => \\Laravel\\Passport\\Http\\Middleware\\CheckClientCredentials::class

I hope that solves issues

Try creating a new password grant client with:

php artisan passport:client --password

You'll get an output like:

What should we name the password grant client? [Laravel Password Grant Client]:
 > 

Password grant client created successfully.
Client ID: 4
Client secret: WlRYEbA5lt5esbi0MuFyJPzPDmHDGsk3iC5QGw7d

Use those credentials to fill your client id and secret. Standard client credentials created through the Vue component interface do not work for password grants.

try to comment middlewares in api middleware group (app/HTTP/Kernel.php)

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
        ],

        'api' => [
//            'throttle:60,1',
//            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

Or comment api middleware group in app/Providers/RouteServiceProvider.php

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

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