2017-03-31 98 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