3

I'm starting to use Web Push Notification; I don't know where I can find the auth key:

var pushSubscription = {
  endpoint: '< Push Subscription URL >',
  keys: {
    p256dh: '< User Public Encryption Key >',
    auth: '< ???? User Auth Secret ???? >'
  }
};

I can get endpoint and p256dh from ServiceWorker>registeration.pushManager.getSubscription() but not the auth key.

Thanks

moeinghasemi
  • 81
  • 1
  • 10
Ali Amini
  • 172
  • 2
  • 14

2 Answers2

11

You can use the getKey method to get both p256dh and auth (see the specs or the example from the specs).

It's even simpler to just call JSON.stringify on the PushSubscription object returned by the getSubscription promise.

Marco Castelluccio
  • 10,152
  • 2
  • 33
  • 48
  • 4
    if you want to use the object (get the keys) in JS, do not fiddle around with ab2string convertions or pushSubscription.keyKeys()... (Spoiler: won't work.) Just do this: `var subJSObject = JSON.parse(JSON.stringify(pushSubscription)); var endpoint = subJSObject.endpoint; var auth = subJSObject.keys.auth; var p256dh = subJSObject.keys.p256dh;` – mondjunge Aug 21 '17 at 10:14
  • @mondjunge You are absolutely right. I chose the hard way and the maximum I could get from all these methods were gibberish. Next time I will look over the specific issue at hand instead try the general solutions like try finding convertion methods. – Luis Febro Oct 08 '21 at 11:42
9

Using Typescript, the PushSubscription object should have a method on it called toJSON. Just use that.

const sub: PushSubscription = YOUR_RAW_PUSH_SUBSCRIPTION;
const pushSubscription = {
  endpoint: sub.endpoint,
  expirationTime: sub.expirationTime,
  keys: {
    p256dh: sub.toJSON().keys.p256dh,
    auth: sub.toJSON().keys.auth
  }
};
Gorgant
  • 381
  • 5
  • 7