自定义Laravel Passport BearerTokenResponse

时间:2016-09-28 09:16:48

标签: php laravel laravel-passport

目前我使用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 repo。

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

1 个答案:

答案 0 :(得分:5)

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

<?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,