Search code examples
phpjwtweb-pushvapid

JWT signature for web push using PHP


I'm trying to send web push notifications using PHP. I have read about how to implement the web push protocol, for instance here. However, I think I don't really get the step where the author of this guide explains how to form the Authorization header. Using this library and given my VAPID keys created by an online generator, I tried the following:

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Ecdsa\Sha256;

$signer = new Sha256();
$privateKey = new Key('<the generated private VAPID key>');
$time = time();

$token = (new Builder())->permittedFor('https://example.com')
                        ->expiresAt($time + 3600)
                        ->withHeader('alg', 'ES256')
                        ->withClaim('sub', 'mailto:someone@example.com')
                        ->getToken($signer, $privateKey);

What I'd like to get is something similar to <JWT Info>.<JWT Data>.<Signature> out of $token. However, I get an Error.

Fatal error: Uncaught InvalidArgumentException: It was not possible to parse your key, reason: error:0909006C:PEM ...

Does somebody know what I'm doing wrong here? Thanks a lot in advance!


Solution

  • Internally, the Lcobucci/jwt API uses both openssl_pkey_get_private() and openssl_pkey_get_public() functions.

    According to the documentation, they expect PEM-encoded keys, and this is not what you supplied. Those kind of keys starts with a -------BEGIN prefix.