Custom Laravel Passport BearerTokenResponse

前端 未结 1 1330
长情又很酷
长情又很酷 2021-01-01 04:11

Currently I have a Laravel installation using Laravel Passport (which uses league/oauth2-server for the server implementation). I would like to return the user

相关标签:
1条回答
  • 2021-01-01 04:58

    To use your custom response, you can add a custom authorization server like this:

    <?php
    
    namespace App;
    
    use League\OAuth2\Server\AuthorizationServer;
    use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
    
    class TokenServer extends AuthorizationServer
    {
        /**
         * Get the token type that grants will return in the HTTP response.
         *
         * @return ResponseTypeInterface
         */
        protected function getResponseType()
        {
            if ($this->responseType instanceof ResponseTypeInterface === false) {
                $this->responseType = new UserIdBearerTokenResponse();
            }
    
            $this->responseType->setPrivateKey($this->privateKey);
    
            return $this->responseType;
        }
    }
    

    And a custom PassportServiceProvider like this:

    <?php
    
    namespace App\Providers;
    
    use App\TokenServer;
    
    class PassportServiceProvider extends \Laravel\Passport\PassportServiceProvider
    {
    
        /**
         * Make the authorization service instance.
         *
         * @return AuthorizationServer
         */
        public function makeAuthorizationServer()
        {
            return new TokenServer(
                $this->app->make(\Laravel\Passport\Bridge\ClientRepository::class),
                $this->app->make(\Laravel\Passport\Bridge\AccessTokenRepository::class),
                $this->app->make(\Laravel\Passport\Bridge\ScopeRepository::class),
                'file://'.storage_path('oauth-private.key'),
                'file://'.storage_path('oauth-public.key')
            );
        }
    
    }
    

    And then make the following change in your config/app.php file:

    /*
     * Package Service Providers...
     * We extend the packaged PassportServiceProvider with our own customization
     */
    
    // Laravel\Passport\PassportServiceProvider::class,
    App\Providers\PassportServiceProvider::class,
    
    0 讨论(0)
提交回复
热议问题