如何使用APNs身份验证密钥和标准CLI工具发送APNs推送消息? [英] How to send APNs push messages using APNs Auth Key and standard CLI tools?

查看:65
本文介绍了如何使用APNs身份验证密钥和标准CLI工具发送APNs推送消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Apple最近向APNS添加了一种新的身份验证方法( Apple推送通知身份验证密钥(沙盒和生产)).

Apple recently added a new authentication method to APNS ( Apple Push Notification Authentication Key (Sandbox & Production)).

下载的密钥是带有私钥的.p8文件:

The downloaded key is a .p8 file with a private key:

$ cat APNSAuthKey_3HHEB343FX.p8
-----BEGIN PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBH...Already.Revoked...lHEjCX1v51W
-----END PRIVATE KEY-----

我正在使用旧方法使用APNs消息-将它们添加到钥匙串中,请求证书并使用OpenSSL将消息发送到gateway.production.push.apple.com:2195.

I am using APNs messages using the old method - adding them to keychain, asking for a certificate and using OpenSSL to send messages to gateway.production.push.apple.com:2195.

如何使用标准的CLI Linux工具(OpenSSL,Python等)以新格式发送推送通知?

推荐答案

如果您的计算机上安装了HTTP/2支持的curl和ECDSA支持的openssl,则可以使用以下脚本使用APNs Auth测试推送通知密钥:

If you have curl with HTTP/2 support and openssl with ECDSA support installed on your machine, you can use the following script to test push notifications using an APNs Auth Key:

#!/bin/bash

deviceToken=b27371497b85611baf9052b4ccfb9641ab7fea1d01c91732149c99cc3ed9342f

authKey="./APNSAuthKey_ABC1234DEF.p8"
authKeyId=ABC1234DEF
teamId=TEAM123456
bundleId=com.example.myapp
endpoint=https://api.development.push.apple.com

read -r -d '' payload <<-'EOF'
{
   "aps": {
      "badge": 2,
      "category": "mycategory",
      "alert": {
         "title": "my title",
         "subtitle": "my subtitle",
         "body": "my body text message"
      }
   },
   "custom": {
      "mykey": "myvalue"
   }
}
EOF

# --------------------------------------------------------------------------

base64() {
   openssl base64 -e -A | tr -- '+/' '-_' | tr -d =
}

sign() {
   printf "$1" | openssl dgst -binary -sha256 -sign "$authKey" | base64
}

time=$(date +%s)
header=$(printf '{ "alg": "ES256", "kid": "%s" }' "$authKeyId" | base64)
claims=$(printf '{ "iss": "%s", "iat": %d }' "$teamId" "$time" | base64)
jwt="$header.$claims.$(sign $header.$claims)"

curl --verbose \
   --header "content-type: application/json" \
   --header "authorization: bearer $jwt" \
   --header "apns-topic: $bundleId" \
   --data "$payload" \
   $endpoint/3/device/$deviceToken

注意::我使用此脚本的一些变体在具有自制软件的版本的curl和openssl的macOS上进行测试:

NOTE: I use a slight variation of this script for testing on macOS with homebrew versions of curl and openssl: http://thrysoee.dk/apns/

这篇关于如何使用APNs身份验证密钥和标准CLI工具发送APNs推送消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆