Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I verify a JSON Web Token using a Public RSA key?

New question to keep this question specific and to the point.

I have a JWT from Azure and now I need verify the signature in my application.

The public keys from Microsoft can be found here:

https://login.windows.net/common/discovery/keys

How do I use these keys to verify a signature? I can tell these these are the public keys I need as the X5T header in the JWT matches those on this public key list.

I am using the JWT PHP library but everything I enter as the public key seems to fail.

supplied key param cannot be coerced into a public key

So using the link above, that goes from there into the PHP openssl_verify function as parameter three ($key in the example below)?

$success = openssl_verify($msg, $signature, $key, 'SHA256')

Everything I enter causes an error in one way or another.

Thanks,

like image 602
Knightsbridge Avatar asked Aug 24 '15 14:08

Knightsbridge


1 Answers

Problem solved.

Turns out that the X5C part of the JSON array is the certificate not public key so JSON decoding https://login.windows.net/common/discovery/keys and grabbing the X5C element and using openssl to derive the public key works:

$cert_object = openssl_x509_read($cert);

$pkey_object = openssl_pkey_get_public(cert_object);

$pkey_array = openssl_pkey_get_details($pkey_object);

$publicKey = $pkey_array ['key'];

In this example $cert is the X5C value. However this on its own is not enough as its not encoded to X509. So what I did is create a new file in windows called certificate.cer, open in notepad and put the X5C value in there. Then by double clicking on ther .cer in windows, navigating to the details tab and clicking "copy to file" this opens the certificate export wizard.

Export as X509 and upload to the server.

$cert = file_get_contents('Certificates/Public/public.cer');

Works! There is probably a simpler way but this works.

like image 178
Knightsbridge Avatar answered Sep 30 '22 07:09

Knightsbridge