Custom Laravel Passport BearerTokenResponse

I currently have a Laravel installation using Laravel Passport (which uses league/oauth2-server to implement the server). I would like to return the user ID when the oauth2 token is provided, so I can use it to identify the authenticated user in my EmberJS application.

The proposed method:

Create my own class:

 use League\OAuth2\Server\ResponseTypes\BearerTokenResponse; use League\OAuth2\Server\Entities\AccessTokenEntityInterface; class UserIdBearerTokenResponse extends BearerTokenResponse { protected function getExtraParams(AccessTokenEntityInterface $accessToken) { return [ 'user_id' => $this->accessToken->getUserIdentifier() ]; } } 

Modification of AuthorizationServer.getResponseType() in vendor/league/oauth2-server/src

 protected function getResponseType() { if ($this->responseType instanceof ResponseTypeInterface === false) { // Return my own class instead of provided one $this->responseType = new UserIdBearerTokenResponse(); } $this->responseType->setPrivateKey($this->privateKey); return $this->responseType; } 

But for this approach, I need to add the vendor/league/oauth2-server/src/AuthorizationServer.php file to my git report.

It seems very dirty and unreliable to me. Is there a better / cleaner way to achieve this?

+1
source share
1 answer

To use your custom response, you can add a custom authorization server as follows:

 <?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 custom PassportServiceProvider:

 <?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 the config / app.php file:

 /* * Package Service Providers... * We extend the packaged PassportServiceProvider with our own customization */ // Laravel\Passport\PassportServiceProvider::class, App\Providers\PassportServiceProvider::class, 
+3
source

Source: https://habr.com/ru/post/1266182/


All Articles