编程语言
首页 > 编程语言> > php – 自定义Laravel Passport BearerTokenResponse

php – 自定义Laravel Passport BearerTokenResponse

作者:互联网

目前我使用Laravel Passport进行Laravel安装(使用联盟/ oauth2服务器进行服务器实现).我想在授予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()
        ];
    }
}

修改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 repo中.

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

解决方法:

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

<?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,laravel-passport
来源: https://codeday.me/bug/20191005/1856621.html