2016-09-28 54 views
1

目前我有一個使用Laravel Passport(它使用league/oauth2-server服務器實現)的Laravel安裝。我想在授予oauth2標記時返回用戶標識,以便我可以使用它在我的EmberJS應用程序中標識經過身份驗證的用戶。自定義Laravel護照BearerTokenResponse

建議的方法來做到這一點:

創建我自己的類:

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() 
     ]; 
    } 
} 

修改AuthorizationServer.getResponseType()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; 
} 

但是這種方法需要我補充vendor/league/oauth2-server/src/AuthorizationServer.php文件到我的git回購。

這對我來說似乎非常混亂和不可靠。有沒有更好的/更清潔的方式來實現這一目標?

+0

它是什麼類型的令牌授權?你如何生成令牌?代碼是什麼樣的? – tptcat

回答

3

能夠使用自定義的響應,你可以添加自定義授權服務器這樣的:

<?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; 
    } 
} 

和一個自定義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') 
     ); 
    } 

} 

然後使你的配置如下變化/app.php文件:

/* 
* Package Service Providers... 
* We extend the packaged PassportServiceProvider with our own customization 
*/ 

// Laravel\Passport\PassportServiceProvider::class, 
App\Providers\PassportServiceProvider::class,