-
-
Save Potherca/46858481f28f745958439d410df42b4a 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
This file contains 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 | |
//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 | |
), | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment