我目前正在使用API,但遇到了麻烦。我正在将Passport与“Password”授予类型一起使用。
我想返回带有访问 token 的用户信息,但是,我不确定该怎么做。
我可以实现,编辑或扩展哪个类以获得此信息?
我希望将其退回:
{
"token_type": "Bearer",
"expires_in": 31536000,
"access_token": "lalalalalal",
"refresh_token": "lalalallala",
"user": {
"username": "a username",
"user_type": "admin"
}
}
提前致谢。
最佳答案
有关如何执行此操作的说明,请参见 BearerTokenResponse
类(League / oauth2-server软件包的一部分)。
在Laravel 5.7上测试。
1.扩展BearerTokenResponse
类,在响应中添加所需的额外参数。
namespace App\Auth;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
class BearerTokenResponse extends \League\OAuth2\Server\ResponseTypes\BearerTokenResponse
{
/**
* Add custom fields to your Bearer Token response here, then override
* AuthorizationServer::getResponseType() to pull in your version of
* this class rather than the default.
*
* @param AccessTokenEntityInterface $accessToken
*
* @return array
*/
protected function getExtraParams(AccessTokenEntityInterface $accessToken): array
{
return [
'user_id' => $this->accessToken->getUserIdentifier(),
];
}
}
2.创建您自己的
PassportServiceProvider
类并覆盖makeAuthorizationServer()
方法,以便传递您自己的BearerTokenResponse
类。 namespace App\Providers;
use App\Auth\BearerTokenResponse;
use Laravel\Passport\Bridge;
use League\OAuth2\Server\AuthorizationServer;
class PassportServiceProvider extends \Laravel\Passport\PassportServiceProvider
{
/**
* Make the authorization service instance.
*
* @return \League\OAuth2\Server\AuthorizationServer
*/
public function makeAuthorizationServer()
{
return new AuthorizationServer(
$this->app->make(Bridge\ClientRepository::class),
$this->app->make(Bridge\AccessTokenRepository::class),
$this->app->make(Bridge\ScopeRepository::class),
$this->makeCryptKey('private'),
app('encrypter')->getKey(),
new BearerTokenResponse() // <-- The class you created above
);
}
}
3.将您的提供商添加到
config/app.php
中的providers数组中 /*
* Application Service Providers...
*/
App\Providers\PassportServiceProvider::class,
4.在
composer.json
中从laravel自动发现中排除护照包这将阻止加载默认的
PassportServiceProvider
类。 "extra": {
"laravel": {
"dont-discover": [
"laravel/passport"
]
}
},
然后运行
composer install
。