问题描述
我目前正在开发 API,但遇到了麻烦.我使用的是密码"授权类型的 Passport.
I am working on an API at the moment and have hit a brick wall. I am using Passport with the 'Password' grant type.
我想用访问令牌返回用户信息,但是,我不知道如何.
I want to return the user information with the access tokens, however, I am not sure how to.
我可以实现、编辑或扩展哪个类来获得它?
Which class could I implement, edit or extend to get this?.
我希望退回:
{
"token_type": "Bearer",
"expires_in": 31536000,
"access_token": "lalalalalal",
"refresh_token": "lalalallala",
"user": {
"username": "a username",
"user_type": "admin"
}
}
提前致谢.
推荐答案
有关如何执行此操作的说明在 BearerTokenResponse
类( League/oauth2-server 包的一部分).
The instructions on how to do this are hinted in the BearerTokenResponse
class (part of the league/oauth2-server package).
在 Laravel 5.7 上测试过.
Tested on Laravel 5.7.
1.扩展 BearerTokenResponse
类,在响应中添加您需要的额外参数.
1. Extend the BearerTokenResponse
class, add the extra params you need in the response.
namespace AppAuth;
use LeagueOAuth2ServerEntitiesAccessTokenEntityInterface;
class BearerTokenResponse extends LeagueOAuth2ServerResponseTypesBearerTokenResponse
{
/**
* 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
类.
2. Create your own PassportServiceProvider
class and override the makeAuthorizationServer()
method in order to pass in your own BearerTokenResponse
class.
namespace AppProviders;
use AppAuthBearerTokenResponse;
use LaravelPassportBridge;
use LeagueOAuth2ServerAuthorizationServer;
class PassportServiceProvider extends LaravelPassportPassportServiceProvider
{
/**
* Make the authorization service instance.
*
* @return LeagueOAuth2ServerAuthorizationServer
*/
public function makeAuthorizationServer()
{
return new AuthorizationServer(
$this->app->make(BridgeClientRepository::class),
$this->app->make(BridgeAccessTokenRepository::class),
$this->app->make(BridgeScopeRepository::class),
$this->makeCryptKey('private'),
app('encrypter')->getKey(),
new BearerTokenResponse() // <-- The class you created above
);
}
}
3.将您的提供程序添加到 config/app.php
/*
* Application Service Providers...
*/
AppProvidersPassportServiceProvider::class,
4.在 composer.json
这会阻止加载默认的 PassportServiceProvider
类.
This stops the default PassportServiceProvider
class from being loaded.
"extra": {
"laravel": {
"dont-discover": [
"laravel/passport"
]
}
},
然后运行composer install
.
这篇关于自定义令牌响应 Laravel Passport的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!