看板 Mesak
作者 標題 [PHP] Laravel passport 取得 accessToken 之後重新產生 jwt
時間 2021-11-02 Tue. 11:34:33
因為第一方特殊需求,response_type 採用code 不採用token 方式直接硬塞 accessToken 授權
https://github.com/laravel/passport/issues/779
namespace App\Eloquent\Passport;
use DateTimeImmutable;
use Laravel\Passport\Passport;
use Lcobucci\JWT\Configuration;
use League\OAuth2\Server\CryptKey;
use Lcobucci\JWT\Signer\Rsa\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use Laravel\Passport\PersonalAccessTokenResult;
class Token extends \Laravel\Passport\Token
{
public function getPersonalAccessTokenResult()
{
$privateKey = new CryptKey(
'file://' . Passport::keyPath('oauth-private.key'),
null,
false
);
$configuration = Configuration::forSymmetricSigner(
new Sha256(),
InMemory::file($privateKey->getKeyPath()),
);
$now = new DateTimeImmutable();
$expiresAt = new DateTimeImmutable($this->expires_at->toDateTimeString());
$token = $configuration->builder()
->permittedFor($this->client_id)
->issuedBy('self')
->identifiedBy($this->id)
->issuedAt($now)
->canOnlyBeUsedAfter($now)
->expiresAt($expiresAt)
->relatedTo($this->user->id)
->withClaim('scopes', [])
->getToken($configuration->signer(), $configuration->signingKey());
return new PersonalAccessTokenResult($token->toString(), $this);
}
}
use DateTimeImmutable;
use Laravel\Passport\Passport;
use Lcobucci\JWT\Configuration;
use League\OAuth2\Server\CryptKey;
use Lcobucci\JWT\Signer\Rsa\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use Laravel\Passport\PersonalAccessTokenResult;
class Token extends \Laravel\Passport\Token
{
public function getPersonalAccessTokenResult()
{
$privateKey = new CryptKey(
'file://' . Passport::keyPath('oauth-private.key'),
null,
false
);
$configuration = Configuration::forSymmetricSigner(
new Sha256(),
InMemory::file($privateKey->getKeyPath()),
);
$now = new DateTimeImmutable();
$expiresAt = new DateTimeImmutable($this->expires_at->toDateTimeString());
$token = $configuration->builder()
->permittedFor($this->client_id)
->issuedBy('self')
->identifiedBy($this->id)
->issuedAt($now)
->canOnlyBeUsedAfter($now)
->expiresAt($expiresAt)
->relatedTo($this->user->id)
->withClaim('scopes', [])
->getToken($configuration->signer(), $configuration->signingKey());
return new PersonalAccessTokenResult($token->toString(), $this);
}
}
AuthServiceProvider::boot 裡面,把 passport 的 tokenModel 換掉
Passport::useTokenModel(\App\Eloquent\Passport\Token::class);
這樣從 user 端 呼叫出來的 tokens token 就能用此方法
$tokenModel = $user->tokens()->where('client_id', $appClient->id )->first();
$tokenResult = $tokenModel->getPersonalAccessTokenResult();
$accessToken = $tokenResult->accessToken;
$tokenResult = $tokenModel->getPersonalAccessTokenResult();
$accessToken = $tokenResult->accessToken;
--
Mesak Blog
http://mesak.tw
--
※ 作者: mesak 時間: 2021-11-02 11:34:33 (台灣)
※ 編輯: mesak 時間: 2021-11-02 11:34:55 (台灣)
※ 看板: Mesak 文章推薦值: 0 目前人氣: 0 累積人氣: 54
回列表(←)
分享