2017-03-31 103 views
4

我正在使用API​​,並且遇到了磚牆。我正在使用「密碼」授權類型的護照。自定義令牌響應Laravel Passport

我想用訪問令牌返回用戶信息,但是,我不知道如何去做。

我可以實現,編輯或擴展哪個類來獲得它?

我想這將返回:提前

{ 
    "token_type": "Bearer", 
    "expires_in": 31536000, 
    "access_token": "lalalalalal", 
    "refresh_token": "lalalallala", 
    "user": { 
     "username": "a username", 
     "user_type": "admin" 
    } 
} 

感謝。

+0

[Custom Laravel Passport BearerTokenResponse]的可能重複(https://stackoverflow.com/questions/39743020/custom-laravel-passport-bearertokenresponse) – simonhamp

回答

-3

你可以輕鬆地做到這一點。打開位於廠商文件BearerTokenResponse.php \聯賽\的oauth2服務器的\ src \ ResponseTypes

修改方法generateHttpResponse(ResponseInterface $響應)這樣的:

public function generateHttpResponse(ResponseInterface $response) 
    { 
     $expireDateTime = $this->accessToken->getExpiryDateTime()->getTimestamp(); 

     $jwtAccessToken = $this->accessToken->convertToJWT($this->privateKey); 

     $responseParams = [ 
      'token_type' => 'Bearer', 
      'expires_in' => $expireDateTime - (new \DateTime())->getTimestamp(), 
      'access_token' => (string) $jwtAccessToken, 
      'user' => User::find($this->accessToken->getUserIdentifier()), 
     ]; 

     if ($this->refreshToken instanceof RefreshTokenEntityInterface) { 
      $refreshToken = $this->encrypt(
       json_encode(
        [ 
         'client_id'  => $this->accessToken->getClient()->getIdentifier(), 
         'refresh_token_id' => $this->refreshToken->getIdentifier(), 
         'access_token_id' => $this->accessToken->getIdentifier(), 
         'scopes'   => $this->accessToken->getScopes(), 
         'user_id'   => $this->accessToken->getUserIdentifier(), 
         'expire_time'  => $this->refreshToken->getExpiryDateTime()->getTimestamp(), 
        ] 
       ) 
      ); 

      $responseParams['refresh_token'] = $refreshToken; 
     } 

     $responseParams = array_merge($this->getExtraParams($this->accessToken), $responseParams); 

     $response = $response 
      ->withStatus(200) 
      ->withHeader('pragma', 'no-cache') 
      ->withHeader('cache-control', 'no-store') 
      ->withHeader('content-type', 'application/json; charset=UTF-8'); 

     $response->getBody()->write(json_encode($responseParams)); 

     return $response; 
    } 

唐忘記使用應用程序\用戶模型。

我希望這對你有所幫助。

+2

您確實不應該編輯供應商文件。有沒有辦法通過覆蓋另一個文件中的功能來做到這一點? – Mike

+0

永遠不要編輯供應商文件,這會造成一個傷害世界。 Laravel更好的選擇是創建一個類似於您想要編輯的類並將其註冊到服務容器中。這樣,您可以覆蓋現有的課程或讓您的新課程一起運行。 – simonhamp

+0

PLease從不迴應供應商編輯... *手掌臉* – AndrewMcLagan