Open dotjm opened 1 year ago
I had the same issue and found the answer here on StackOverFlow : https://stackoverflow.com/questions/51327584/how-to-generate-key-pair-for-php-jwt
1) generate private key:
openssl genrsa -out private.pem 2048
2) extract public key from private key:
openssl rsa -in private.pem -outform PEM -pubout -out public.pem
3) and example php code:
<?php
require_once('vendor/autoload.php');
use \Firebase\JWT\JWT;
$privateKey = file_get_contents('./private.pem');
$publicKey = file_get_contents('./public.pem');
$payload = [
'data' => ['field1' => 1, 'field2' => 'string data'],
"iss" => "http://example.org",
"aud" => "http://example.com",
"iat" => 1531498466,
"eat" => 1557000000
];
$token = JWT::encode($payload, $privateKey, 'RS256');
echo "Token:\n" . print_r($token, true) . "\n";
$decoded = JWT::decode($token, $publicKey, ['RS256']);
$decoded_array = (array) $decoded;
echo "Decoded:\n" . print_r($decoded_array, true) . "\n";
Bonus: HS256 example
Since HS256 is symmetric algorithm, it does not require private/public key pairs.
You may use Your own blablabla-like random secret string, without using generators and etc:
<?php
require_once('vendor/autoload.php');
use \Firebase\JWT\JWT;
$secret = 'blablabla-secret-string';
// or You can save that random text in .jwt-secret file and use this way
// $secret = file_get_contents('./.jwt-secret');
$payload = [
'data' => ['field1' => 1, 'field2' => 'string data'],
"iss" => "http://example.org",
"aud" => "http://example.com",
"iat" => 1531498466,
"eat" => 1557000000
];
$token = JWT::encode($payload, $secret, 'HS256');
echo "HS256 Token:\n" . print_r($token, true) . "\n";
$decoded = JWT::decode($token, $secret, ['HS256']);
$decoded_array = (array) $decoded;
echo "HS256 Token decoded:\n" . print_r($decoded_array, true) . "\n";
I don't understand "How i set '$privateKey'". Because i create my key file (private.key)
But didn't working.... with error : openssl_sign(): supplied key param cannot be coerced into a private key I just set $privateKey to text of privateKey at example code. What the heck should I do... I need a detailed manual...