lindelius/php-jwt

Signature key?

Andrewsuares opened this issue · 2 comments

Hello,

Is a key required to sign the token? How do we do that?

Thanks

Hi @Andrewsuares,

Yes, you do indeed need a key to sign the token. For the default algorithm (HS256) or any of the other HMAC algorithms (HS384 and HS512), the key can be any string of your choice. If you're using the library with a framework, e.g. Laravel, you could use the application key for this purpose. For these algorithms you use the same key both when you sign and when you verify a token.

// Get the secret key to use when signing the token
$key = 'yourVerySecretKeyString';

// Create the token
$jwt = new \Lindelius\JWT\JWT();

$jwt->exp = time() + (60 * 60 * 2);
$jwt->iat = time();
$jwt->sub = $user->id;

// Sign the token using the secret key
$token = $jwt->encode($key);

However, if you're using one of the RSA algorithms (RS256, RS384, or RS512), then you need to use a special RSA key for this. You may use the code below for generating a public/private key pair. The key generation should preferably not be performed during the actual request to your application, though, as the generation is a quite heavy operation. Also, note that you have to use the private key when you sign the token and then the public key when you verify the token.

// Generate a new RSA public/private key pair
$privateKey = null;
$resource   = openssl_pkey_new();

openssl_pkey_export($resource, $privateKey);

$publicKey = openssl_pkey_get_details($resource)['key'];

// Create the token
$jwt = new \Lindelius\JWT\JWT('RS256');

$jwt->exp = time() + (60 * 60 * 2);
$jwt->iat = time();
$jwt->sub = $user->id;

// Sign the token using the private key
$token = $jwt->encode($privateKey);

Hi @Andrewsuares,

I'm closing this issue, but feel free to reopen it if you are still having problems.