Return 使用 Passport 和 Laravel 进行身份验证时的访问令牌和用户

Return the access token and the user when authenticating using Passport and Laravel

我正在使用 Laravel 5.4 和 Passport 创建 API。 API 授权使用密码授予类型完成。

下面是一个示例请求:

$http = new GuzzleHttp\Client;
$response = $http->post('http://your-app.com/oauth/token', [
  'form_params' => [
     'grant_type' => 'password',
     'client_id' => 'client-id',
     'client_secret' => 'client-secret',
     'username' => 'taylor@laravel.com',
     'password' => 'my-password',
     'scope' => '',
   ],
]);

return json_decode((string) $response->getBody(), true);

这将向“/oauth/token”发送一个 POST 请求,响应如下:

{
  "token_type": "Bearer",
  "expires_in": 3155673600,
  "access_token": "eyJ0eXAiOiJK...",
  "refresh_token": "LbxXGlD2s..."
}

我想要的是得到一个包含经过身份验证的用户的响应,如下所示:

[
  data:{
     name: Jhon,
     email: jhon@example.com,
     address: ASDF Street no.23
  },
  token{
     "token_type": "Bearer",
     "expires_in": 3155673600,
     "access_token": "eyJ0eXAiOiJK...",
     "refresh_token": "LbxXGlD2s..."
  }
]

我已经在第 65 行更改了 PasswordGrant 文件

vendor/league/oauth2-server/src/Grant/PasswordGrant.php

$responseType->setAccessToken($accessToken);
$responseType->setRefreshToken($refreshToken);
return $responseType;

我希望有人能帮助我,并告诉我如何解决这个问题, 谢谢。

您可以编写一个 (after-) middleware 来接受原始响应并将其转换为您想要的方式。但请注意,所有其他 Passport 中间件(CheckClientCredentialsCheckScopesCreateFreshApiToken 等)可能取决于该特定格式,并且也必须进行调整。