gpt4 book ai didi

php - 自定义 Laravel 护照 BearerTokenResponse

转载 作者:行者123 更新时间:2023-12-02 18:55:28 26 4
gpt4 key购买 nike

目前我有一个使用 Laravel Passport 的 Laravel 安装(它使用 league/oauth2-server 作为服务器实现)。我想在授予 oauth2 token 时返回用户 ID,以便我可以使用它来识别我的 EmberJS 应用程序中经过身份验证的用户。

建议的方法是:

创建我自己的类(class):

use League\OAuth2\Server\ResponseTypes\BearerTokenResponse;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;

class UserIdBearerTokenResponse extends BearerTokenResponse
{
protected function getExtraParams(AccessTokenEntityInterface $accessToken)
{
return [
'user_id' => $this->accessToken->getUserIdentifier()
];
}
}

修改vendor/league/oauth2-server/src中的AuthorizationServer.getResponseType()

protected function getResponseType()
{
if ($this->responseType instanceof ResponseTypeInterface === false) {
// Return my own class instead of provided one
$this->responseType = new UserIdBearerTokenResponse();
}

$this->responseType->setPrivateKey($this->privateKey);

return $this->responseType;
}

但这种方法需要我将 vendor/league/oauth2-server/src/AuthorizationServer.php 文件添加到我的 git 存储库中。

这对我来说似乎非常困惑和不可靠。有没有更好/更干净的方法来实现这一目标?

最佳答案

要使用自定义响应,您可以添加自定义授权服务器,如下所示:

<?php

namespace App;

use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;

class TokenServer extends AuthorizationServer
{
/**
* Get the token type that grants will return in the HTTP response.
*
* @return ResponseTypeInterface
*/
protected function getResponseType()
{
if ($this->responseType instanceof ResponseTypeInterface === false) {
$this->responseType = new UserIdBearerTokenResponse();
}

$this->responseType->setPrivateKey($this->privateKey);

return $this->responseType;
}
}

还有一个像这样的自定义 PassportServiceProvider:

<?php

namespace App\Providers;

use App\TokenServer;

class PassportServiceProvider extends \Laravel\Passport\PassportServiceProvider
{

/**
* Make the authorization service instance.
*
* @return AuthorizationServer
*/
public function makeAuthorizationServer()
{
return new TokenServer(
$this->app->make(\Laravel\Passport\Bridge\ClientRepository::class),
$this->app->make(\Laravel\Passport\Bridge\AccessTokenRepository::class),
$this->app->make(\Laravel\Passport\Bridge\ScopeRepository::class),
'file://'.storage_path('oauth-private.key'),
'file://'.storage_path('oauth-public.key')
);
}

}

然后在 config/app.php 文件中进行以下更改:

/*
* Package Service Providers...
* We extend the packaged PassportServiceProvider with our own customization
*/

// Laravel\Passport\PassportServiceProvider::class,
App\Providers\PassportServiceProvider::class,

关于php - 自定义 Laravel 护照 BearerTokenResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39743020/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com