VAPID public 密钥是否与 applicationServerKey 客户端相同?

Is the VAPID public key the same as applicationServerKey client-side?

在客户端,要订阅网络推送通知,您需要使用 applicationServerKey 选项调用 subscribe,如下所示:

var serviceWorkerRegistration = ...
serviceWorkerRegistration.pushManager.subscribe({
  userVisibleOnly: true,
  applicationServerKey: urlB64ToUint8Array("......")
}).then(function(subscription) {
   ...
})

您可以将 subscription 对象发送到服务器,在那里可以保存它。

要向订阅者发送推送消息,服务器需要post到对象subscription中的键endpoint指示的URL。服务器需要使用 VAPID 向提供商(Mozilla 或 Google 或其他任何人)标识自己。例如,使用 Python 库 pywebpush,将进行此调用:

import pywebpush
pywebpush.webpush(
    subscription,
    data,
    vapid_private_key="path_to_private_key.pem",
    vapid_claims={"sub": "mailto:example@example.com"},
)

这是我的问题:

用于发送推送消息的私有 VAPID 密钥是否与客户端传递给 serviceWorkerRegistration.pushManager.subscribe 的 public 密钥相对应?或者它属于一个单独的密钥对?我的直觉告诉我它应该属于同一个密钥对,但是术语 VAPID 只在谈论发送推送消息时被提及,而不是在订阅时被提及,所以我不确定这个假设是否正确。

是的,属于同一个keypair。这篇博客postWeb Push Interoperability Wins说得更清楚了:

The process is pretty simple:

  1. Your application server creates a public/private key pair. The public key is given to your web app.
  2. When the user elects to receive pushes, add the public key to the subscribe() call's options object.
  3. When your app server sends a push message, include a signed JSON Web Token along with the public key.

根据您在服务器上使用的库,您可能需要不同格式的私钥。例如,pywebpush for Python 需要 VAPID EC2 私钥 PEM 文件,或 DER 格式和 base64 的字符串。