Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow for customization of the builder class #33

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
"mockery/mockery": "^1.4",
"orchestra/testbench": "^7.0|^8.0",
"phpseclib/phpseclib": "^3.0",
"phpseclib/phpseclib2_compat": "^1.0"
"phpseclib/phpseclib2_compat": "^1.0",
"nunomaduro/collision": "^6.2"
},
"autoload": {
"psr-4": {
Expand Down
14 changes: 13 additions & 1 deletion config/passport-claims.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,17 @@
*/
'claims' => [
// App\Claims\CustomClaim::class
]
],

/*
|--------------------------------------------------------------------------
| JWT Custom Builder
|--------------------------------------------------------------------------
|
| Here you can change which class implements the convertToJWT method.
| The class requires method convertToJWT() : Token to return a custom
| token builder for the pipeline. It must be a private function.
|
*/
'builder' => \CorBosman\Passport\AccessToken::class
];
4 changes: 3 additions & 1 deletion src/AccessTokenRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace CorBosman\Passport;

use Laravel\Passport\Passport;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use Laravel\Passport\Bridge\AccessTokenRepository as PassportAccessTokenRepository;

Expand All @@ -12,6 +13,7 @@ class AccessTokenRepository extends PassportAccessTokenRepository
*/
public function getNewToken(ClientEntityInterface $clientEntity, array $scopes, $userIdentifier = null)
{
return new AccessToken($userIdentifier, $scopes, $clientEntity);
\Laravel\Passport\Passport::useAccessTokenEntity(config('passport-claims.builder', AccessToken::class));
return new \Laravel\Passport\Passport::$accessTokenEntity($userIdentifier, $scopes, $clientEntity);
}
}
8 changes: 7 additions & 1 deletion src/ServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ class ServiceProvider extends \Illuminate\Support\ServiceProvider
public function boot()
{
if (method_exists(Passport::class, 'useAccessTokenEntity')) {
Passport::useAccessTokenEntity(AccessToken::class);
// I'm actually a little confused about this I may need a better way to test this
Passport::useAccessTokenEntity(config('passport-claims.builder', AccessToken::class));
} else {
$this->app->bind(PassportAccessTokenRepository::class, AccessTokenRepository::class);
}
Expand All @@ -35,4 +36,9 @@ protected function bootForConsole()

$this->commands([ClaimGenerator::class]);
}

public function register(): void
{
$this->mergeConfigFrom(__DIR__ . '/../config/passport-claims.php', 'passport-claims');
}
}
45 changes: 45 additions & 0 deletions tests/Builders/CustomAccessTokenBuilderAddsIssuer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace CorBosman\Passport\Tests\Builders;

use CorBosman\Passport\ClaimsFormatter;
use CorBosman\Passport\Traits\ClaimTrait;
use Illuminate\Pipeline\Pipeline;
use Laravel\Passport\Bridge\AccessToken as PassportAccessToken;
use Lcobucci\JWT\Token;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
use League\OAuth2\Server\Entities\Traits\AccessTokenTrait;
use \DateTimeImmutable;

class CustomAccessTokenBuilderAddsIssuer extends PassportAccessToken implements AccessTokenEntityInterface
{
use AccessTokenTrait, ClaimTrait;

/**
* Generate a JWT from the access token
*
* @return Token
*/
private function convertToJWT() : Token
{
$this->initJwtConfiguration();

$jwt = $this->jwtConfiguration->builder(ClaimsFormatter::formatters())
->permittedFor($this->getClient()->getIdentifier())
->identifiedBy($this->getIdentifier())
->issuedAt(new DateTimeImmutable())
->canOnlyBeUsedAfter(new DateTimeImmutable())
->expiresAt($this->getExpiryDateTime())
->relatedTo((string) $this->getUserIdentifier())
->withClaim('scopes', $this->getScopes())
->issuedBy('CustomTokenIssuer');

return collect(app(Pipeline::class)
->send($this)
->through(config('passport-claims.claims', []))
->thenReturn()
->claims())
->reduce(fn($jwt, $value, $key) => $jwt->withClaim($key, $value), $jwt)
->getToken($this->jwtConfiguration->signer(), $this->jwtConfiguration->signingKey());
}
}
53 changes: 53 additions & 0 deletions tests/CustomBuilderClassTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

namespace CorBosman\Passport\Tests;

use CorBosman\Passport\ServiceProvider;
use CorBosman\Passport\Tests\Builders\CustomAccessTokenBuilderAddsIssuer;
use Lcobucci\JWT\Encoding\JoseEncoder;
use Mockery as m;
use Lcobucci\JWT\Token\Parser;
use phpseclib\Crypt\RSA;
use Carbon\CarbonImmutable;
use Orchestra\Testbench\TestCase;
use League\OAuth2\Server\CryptKey;
use Laravel\Passport\Bridge\Client;
use Laravel\Passport\TokenRepository;
use Illuminate\Contracts\Events\Dispatcher;
use CorBosman\Passport\Tests\Claims\MyClaim;
use CorBosman\Passport\AccessTokenRepository;
use CorBosman\Passport\Tests\Claims\AnotherClaim;

class CustomBuilderClassTest extends TestCase
{
protected function tearDown(): void
{
m::close();
}

public function test_can_add_custom_builder()
{
/* set custom token builder */
app('config')->set('passport-claims.builder', CustomAccessTokenBuilderAddsIssuer::class);

/* set up the environment */
$repository = new AccessTokenRepository(m::mock(TokenRepository::class), m::mock(Dispatcher::class));
$client = new Client('client-id', 'name', 'redirect');
$scopes = [];
$userIdentifier = 1;
$keys = (new RSA())->createKey(2048);

/* create the laravel token */
$token = $repository->getNewToken($client, $scopes, $userIdentifier);
$token->setPrivateKey(new CryptKey($keys['privatekey']));
$token->setExpiryDateTime(CarbonImmutable::now()->addHour());
$token->setIdentifier('test');

/* convert the token to a JWT and parse the JWT back to a Token */
$jwt = (new Parser(new JoseEncoder))->parse($token->__toString());

/* assert our claims were set on the token */
$this->assertEquals(true, $jwt->hasBeenIssuedBy('CustomTokenIssuer'));
}
}

Loading