Created
January 28, 2021 00:01
-
-
Save kmuenkel/49ae82def535c800d6afefbca0419b80 to your computer and use it in GitHub Desktop.
PhpUnit Token generators and parsers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Tests; | |
use Firebase\JWT\JWT; | |
use Laravel\Passport\Passport; | |
use Illuminate\Support\Facades\File; | |
/** | |
* Trait TokenHelpers | |
* @package Tests | |
*/ | |
trait TokenHelpers | |
{ | |
/** | |
* @param array $payload | |
* @param array $scopes | |
* @param string $oauthRoute | |
* @return string | |
*/ | |
protected function generateOauthToken(array $payload, array $scopes, string $oauthRoute = 'passport.token'): string | |
{ | |
$assertion = JWT::encode($payload, $this->oauthKeys()['private'], 'RS256'); | |
$credentials = [ | |
'grant_type' => 'client_credentials', | |
'client_assertion_type' => 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', | |
'scope' => implode(',', $scopes), | |
'client_assertion' => $assertion | |
]; | |
PassportModels\DummyClient::$staticAttributes = [ | |
'id' => 1, | |
'name' => $payload['iss'] | |
]; | |
Passport::$clientModel = PassportModels\DummyClient::class; | |
PassportModels\DummyToken::$dummyClient = app(PassportModels\DummyClient::class); | |
Passport::$tokenModel = PassportModels\DummyToken::class; | |
$response = $this->post(route($oauthRoute), $credentials); | |
return $response->json('token_type').' '.$response->json('access_token'); | |
} | |
/** | |
* @param bool $fresh | |
* @return string[] | |
*/ | |
protected function oauthKeys(bool $fresh = false): array | |
{ | |
if ($this->oauthKeys && !$fresh) { | |
return $this->oauthKeys; | |
} | |
Passport::$keyPath = __DIR__.'/Resources/credentials'; | |
$this->artisan('passport:keys'/*, ['--force' => true]*/); | |
$privateKey = File::get(Passport::$keyPath.'/oauth-private.key'); | |
$publicKey = File::get(Passport::$keyPath.'/oauth-public.key'); | |
return $this->oauthKeys = [ | |
'private' => $privateKey, | |
'public' => $publicKey | |
]; | |
} | |
/** | |
* @param string $jwt | |
* @return string[] | |
*/ | |
protected function decode(string $jwt): array | |
{ | |
$segments = explode('.', $jwt); | |
$segments = array_pad($segments, 3, ''); | |
$jsonKeys = ['head', 'body']; | |
$keys = array_merge($jsonKeys, ['crypto']); | |
$segments = array_map(function (string $segment, string $name) use ($jsonKeys) { | |
$segment = JWT::urlsafeB64Decode($segment); | |
in_array($name, $jsonKeys) && $segment = JWT::jsonDecode($segment); | |
return $segment; | |
}, $segments, $keys); | |
$segments = array_combine($keys, $segments); | |
return $segments; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment