Skip to content

Instantly share code, notes, and snippets.

@sicet7
Last active September 6, 2023 16:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sicet7/115bfe433e9f6f68d892c5966ed33ebb to your computer and use it in GitHub Desktop.
Save sicet7/115bfe433e9f6f68d892c5966ed33ebb to your computer and use it in GitHub Desktop.
Use JWK from JSON with the lcobucci/jwt library through phpseclib. Credit to @whatTool for helping with the implementation
<?php
//REQUIREMENTS!
//"phpseclib/phpseclib": "^3.0"
//"lcobucci/jwt": "^5.0"
require_once __DIR__ . '/vendor/autoload.php';
$json = '{
"keys": [
{
"kid":"my key id",
"nbf":1493763266,
"use":"sig",
"kty":"RSA",
"e":"something something JWK stuff",
"n":"something something JWK stuff"
}
]
}';
function getKeyFromJwkJson(string $kid, string $jwkKeySet): ?\Lcobucci\JWT\Signer\Key
{
$data = json_decode($jwkKeySet, true, 512, JSON_THROW_ON_ERROR);
if (
!is_array($data) ||
!array_key_exists('keys', $data) ||
!is_array($data['keys']) ||
empty($data['keys'])
) {
return null;
}
foreach ($data['keys'] as $key) {
//TODO: handle nbf on keys
if (($key['kid'] ?? '') == $kid) {
$publicKey = \phpseclib3\Crypt\PublicKeyLoader::load(
\phpseclib3\Crypt\RSA\Formats\Keys\JWK::load(
json_encode($key, JSON_THROW_ON_ERROR)
)
);
return \Lcobucci\JWT\Signer\Key\InMemory::plainText(
$publicKey->toString('pkcs8')
);
}
}
return null;
}
$key = getKeyFromJwkJson('my key id', $json);
if ($key === null) {
//no key found
exit(1);
}
$constraints = [
new \Lcobucci\JWT\Validation\Constraint\SignedWith(
new \Lcobucci\JWT\Signer\Rsa\Sha256(),
$key
),
];
@dotmra
Copy link

dotmra commented Jul 4, 2023

Made with Azure B2C in mind, where there can be multiple keys and the JWT has the kid in the header.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment