4

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

建议的方法是:

创建我自己的类:

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()
        ];
    }
}

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

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 存储库中。

这对我来说似乎非常混乱和不可靠。有没有更好/更清洁的方法来实现这一目标?

4

1 回答 1

6

要使用您的自定义响应,您可以像这样添加自定义授权服务器:

<?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,
于 2016-10-28T13:45:39.880 回答