Customising token response Laravel Passport

后端 未结 5 1489
被撕碎了的回忆
被撕碎了的回忆 2020-12-16 11:34

I am working on an API at the moment and have hit a brick wall. I am using Passport with the \'Password\' grant type.

I want to return the user information with the

5条回答
  •  萌比男神i
    2020-12-16 11:58

    Im using Multi-Auth with passport, so the previous answers didn't help me.

    After hours of "googling" I found this answer (after-) middleware.

    My middleware basically gets the result of Passport auth, checks if there is an Bearer inside and append more data to the content.

    content(), true);
    
            if (!empty($content['access_token'])) {
    
                $content['moredata'] = 'some data';
    
                $response->setContent($content);
    
            }
    
            return $response;
        }
    }
    

    Now put the new Middleware in $routemiddleware at App/Http/Kernel.php

     /**
         * The application's route middleware.
         *
         * These middleware may be assigned to groups or used individually.
         *
         * @var array
         */
        protected $routeMiddleware = [
            'auth' => \App\Http\Middleware\Authenticate::class,
            'cors' => \App\Http\Middleware\Cors::class,
            'multiauth' => \SMartins\PassportMultiauth\Http\Middleware\MultiAuthenticate::class,
            'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
            'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
            'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
            'can' => \Illuminate\Auth\Middleware\Authorize::class,
            'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
            'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
            'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
            'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
            'oauth.providers' => \SMartins\PassportMultiauth\Http\Middleware\AddCustomProvider::class,
            'append_auth' =>\App\Http\Middleware\AppendTokenResponse::class,
    
        ];
    

    Then just register this middleware to Passport Routes in Providers/AuthServiceProvider.php

    With Multiauth:

    Route::group(['middleware' => ['oauth.providers','append_auth']], function () {
        Passport::routes(function ($router) {
            return $router->forAccessTokens();
        });
    });
    

    I believe regular passport should be (not tested):

    Route::group(['middleware' => ['append_auth']], function () {
        Passport::routes();
    });
    

提交回复
热议问题