【问题标题】:Web Notification Push Subscription what to do with auth?Web 通知推送订阅如何处理身份验证?
【发布时间】:2018-07-25 14:35:06
【问题描述】:

网络通知订阅回发可能会提供以下数据:

{
    "customerid": "123456",
    "subscription": {
        "endpoint": "https://updates.push.services.mozilla.com/push/v1/gAAAA…",
        "keys": {
            "p256dh": "BOrnIslXrUow2VAzKCUAE4sIbK00daEZCswOcf8m3TF8V…",
            "auth": "k8JV6sjdbhAi1n3_LDBLvA"
         }
    },
    "favoritedrink": "warm milk"
}

我觉得我错过了一些东西,因为我不知道如何处理身份验证数据 (k8JV6sjdbhAi1n3_LDBLvA),它是如何使用的?

【问题讨论】:

    标签: web-notifications


    【解决方案1】:

    我想出了使用这个库来做什么:https://github.com/web-push-libs/web-push-csharp

    核弹

    Install-Package WebPush
    
    
    
    public static string Encode(byte[] data)
            {
                return Convert.ToBase64String(data).Replace('+', '-').Replace('/', '_').TrimEnd('=');
            }
    
         public static AsymmetricCipherKeyPair GenerateKeys()
                {
                    var ecParameters = NistNamedCurves.GetByName("P-256");
                    var ecSpec = new ECDomainParameters(ecParameters.Curve, ecParameters.G, ecParameters.N, ecParameters.H,
                        ecParameters.GetSeed());
                    var keyPairGenerator = GeneratorUtilities.GetKeyPairGenerator("ECDH");
                    keyPairGenerator.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));
    
                    return keyPairGenerator.GenerateKeyPair();
                }
    
    public string privateKeyStr;
    public string publicKeyStr;
    
    public void DoWork()
    {
      byte[] publicKey = ((ECPublicKeyParameters)keys.Public).Q.GetEncoded(false);
                byte[] privateKey = ((ECPrivateKeyParameters)keys.Private).D.ToByteArrayUnsigned();
                privateKeyStr = Encode(privateKey);
                publicKeyStr = Encode(publicKey);
    
    // Save/Restore privateKeyStr / publicKeyStr (don't want to gen each time)
    
    // now publicKeyStr needs to be an input into the ServiceWoker reg in javascript
    

    例如

    const serviceWorker = navigator.serviceWorker.register('serviceworkerloader.js', { scope: './' }).then(
        function (swReg) {
            console.log('Service Worker is registered', swReg);
            swRegistration = swReg;
    
            swRegistration.pushManager.getSubscription()
                .then(function (subscription) {
                    let isSubscribed = !(subscription === null)
    
                    if (isSubscribed) {
                        console.log('User IS subscribed.')
    
                        let unsub = false
                        if (unsub) {
                            subscription.unsubscribe()
                        }
                    } else {
                        console.log('User is NOT subscribed.')
                    }
                });
    
            // subscribe
            const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
            swRegistration.pushManager.subscribe({
                userVisibleOnly: true,
                applicationServerKey: applicationServerKey
            }).then(function (subscription) {
                updateSubscriptionOnServer(subscription);
                isSubscribed = true
            }).catch(function (err) {
                console.log('Failed to subscribe the user: ', err);
            });
    
        })
    

    这样返回数据:

    {
        "customerid": "123456",
        "subscription": {
            "endpoint": "https://updates.push.services.mozilla.com/push/v1/gAAAA…",
            "keys": {
                "p256dh": "BOrnIslXrUow2VAzKCUAE4sIbK00daEZCswOcf8m3TF8V…",
                "auth": "k8JV6sjdbhAi1n3_LDBLvA"
             }
        },
        "favoritedrink": "warm milk"
    }
    

    必须将其返回到您的服务器,然后您才能运行此代码:

        var pushEndpoint = @"https://fcm.googleapis.com/fcm/send/clKG12Pq-vQ:APA91bGvMOg0lgnAiHvN6X8AOh0hVN5KsGrdXNC9zka0uIbZUTbbypcd5Ns7pamt2tQcKvedZVm_i7tW996wN82pnx4ks1dH022cPm_GDLW0SsHwwLtvGgWGJ1grANp04GuwiNZQ9rhpb2X8FsjqIYL499Q49LydRg";
        var p256dh = @"BDSRQDB8Okr85gC7V4YMQEHsEMxBjOoN1GTdsnL9CcyZ_xrvna1u1AV9yoYBWZ80dNKzeMSqWhybMGvFkPuDq6s";
        var auth = @"oKospnY_RDj_EiRsn-PwuA";
    
        var subject = @"mailto:example@example.com";
        var publicKey = generatedPublicKey;
        //@"BDjASz8kkVBQJgWcD05uX3VxIs_gSHyuS023jnBoHBgUbg8zIJvTSQytR8MP4Z3-kzcGNVnM...............";
        var privateKey = generatedPrivateKey;
            //@"mryM-krWj_6IsIMGsd8wNFXGBxnx...............";
    
        var subscription = new PushSubscription(pushEndpoint, p256dh, auth);
        var vapidDetails = new VapidDetails(subject, publicKey, privateKey);
        //var gcmAPIKey = @"[your key here]";
    
        var webPushClient = new WebPushClient();
        try
        {
            webPushClient.SendNotification(subscription, "payload", vapidDetails);
            //webPushClient.SendNotification(subscription, "payload", gcmAPIKey);
        }
        catch (WebPushException exception)
        {
            Console.WriteLine("Http STATUS code" + exception.StatusCode);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 2021-10-16
      • 1970-01-01
      相关资源
      最近更新 更多