laraveloauthlaravel-passportapi-versioning

Laravel - API Versioning /v2/ endpoints always return 401


I'm currently working on a Laravel API which uses Laravel Passport (OAuth2). I recently added a v2 to my Laravel application API. Everything works fine on my local machine. But on my TEST-Server, the application always throws a 401 when I send a request to a v2 endpoint.

Here is my setup:

RouteServiceProvider:

protected function mapApiRoutes()
{
    Route::group([
        'middleware' => ['api', 'api_version:v1'],
        'namespace'  => "{$this->namespace}",
        'prefix'     => 'api',
    ], function ($router) {
        require base_path('routes/api.php');
    });    
    Route::group([
        'middleware' => ['api', 'api_version:v2'],
        'namespace'  => "{$this->namespace}\V2",
        'prefix'     => 'api/v2',
    ], function ($router) {
        require base_path('routes/api/api_v2.php');
    });
}

auth.php:

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

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],

    'api_v2' => [
        'driver' => 'passport',
        'provider' => 'users_v2',
    ],
],

// ...

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\Base\User::class,
    ],
    'users_v2' => [
        'driver' => 'eloquent',
        'model' => App\Models\V2\Base\User::class,
    ],
],

routes/api_v2.php:

Route::group(['middleware' => ['auth:api_v2']], function() {
    Route::get('user', 'Base\UserController@authUserV2');
    // ...
});

APIVersion Middleware:

public function handle(Request $request, Closure $next, $guard)
{
    if ($guard != 'v1') {
        // Morph user model
        $apiVersion = $guard == '' ? '' : ('\\' . strtoupper($guard) . '\\');
        Relation::morphMap([
            'App\User' => 'App\Models\Base\User',
            'App\Models\Base\User' => 'App\Models' . $apiVersion . 'Base\User'
        ]);

    config(['app.api.version' => $guard]);
    return $next($request);
}

The request throws a 401 before the APIVersion middleware is executed.

I don't know why it works on my local machine, but not on my Test server. Is this error code or machine related?

Edit

I found out, that as soon as I change the guard of api_v2 back to users instead of users_v2 It works. But then it does not use the V2 User Model, which of course throws errors in my Controllers.


Solution

  • After hours of searching, I found my problem. The database of my local machine has an older oauth_clients table, which doesn't contain the provider column. After changing the provider column on my Test Server to NULL, everything is working fine!

    Does someone know if it is possible to specify multiple providers in this column instead of allowing all?