iOS的APNs

Communicating with APNs

The APNs provider API lets you send remote notifications to your app on iOS, tvOS, and macOS devices, and to Apple Watch via iOS. The API is based on the HTTP/2 network protocol. Each interaction starts with a POST request, containing a JSON payload, that you send from your provider server to APNs. APNs then forwards the notification to your app on a specific user device.

Provider Authentication Tokens

To securely connect to APNs, you can use provider authentication tokens or provider certificates. This section describes connections using tokens.

The provider API supports the JSON Web Token (JWT) specification, letting you pass statements and metadata, called claims, to APNs, along with each push notification. For details, refer to the specification at https://tools.ietf.org/html/rfc7519. For additional information about JWT, along with a list of available libraries for generating signed JWTs, see https://jwt.io

A provider authentication token is a JSON object that you construct, whose header must include:

*The encryption algorithm (alg) you use to encrypt the token

*A 10-character key identifier (kid) key, obtained from your developer account

The claims payload of the token must include:

The issuer (iss) registered claim key, whose value is your 10-character Team ID, obtained from your developer account

The issued at (iat) registered claim key, whose value indicates the time at which the token was generated, in terms of the number of seconds since Epoch, in UTC

After you create the token, you must sign it with a private key. You must then encrypt the token using the Elliptic Curve Digital Signature Algorithm (ECDSA) with the P-256 curve and the SHA-256 hash algorithm. Specify the value ES256 in the algorithm header key (alg). For information on how to configure your token, search Xcode help for the phrase “Configure push notifications.”

A decoded JWT provider authentication token for APNs has the following format:

{    

    "alg": "ES256",   

    "kid": "ABC123DEFG"

}

{   

 "iss": "DEF123GHIJ",    

"iat": 1437179036 

}

NOTE

APNs supports only provider authentication tokens that are signed with the ES256 algorithm. Unsecured JWTs, or JWTs signed with other algorithms, are rejected, and your provider server receives the InvalidProviderToken (403) response.

To ensure security, APNs requires new tokens to be generated periodically. A new token has an updated issued at claim key, whose value indicates the time the token was generated. If the timestamp for token issue is not within the last hour, APNs rejects subsequent push messages, returning an ExpiredProviderToken (403) error.


If you suspect your provider token signing key is compromised, you can revoke it from your developer account. You can issue a new key pair and can then generate new tokens with the new private key. For maximum security, close all your connections to APNs that had been using tokens signed with the now-revoked key, and reconnect before using tokens signed with the new key.

APNs Provider Certificates

Your APNs provider certificate, which you obtain as explained in "Configure push notifications” in Xcode help, enables connection to both the APNs Production and Development environments.

You can use your APNs certificate to send notifications to your primary app, as identified by its bundle ID, as well as to any Apple Watch complications or backgrounded VoIP services associated with that app. Use the ( 1.2.840.113635.100.6.3.6 ) extension in the certificate to identify the topics for your push notifications. For example, if you provide an app with the bundle ID com.yourcompany.yourexampleapp, you can specify the following topics in the certificate:

Extension ( 1.2.840.113635.100.6.3.6 )

Critical NO

Data com.yourcompany.yourexampleapp

Data app

Data com.yourcompany.yourexampleapp.voip

Data voip

Data com.yourcompany.yourexampleapp.complication

Data complication

APNs Connections

The first step in sending a remote notification is to establish a connection with the appropriate APNs server:

Development server: api.development.push.apple.com:443

Production server: api.push.apple.com:443

NOTE

You can alternatively use port 2197 when communicating with APNs. You might do this, for example, to allow APNs traffic through your firewall but to block other HTTPS traffic.

Your provider server must support TLS 1.2 or higher when connecting to APNs. You can use the provider client certificate which you obtain from your developer account, as described in Creating a Universal Push Notification Client SSL Certificate.

To connect without an APNs provider certificate, you must instead create a provider authentication token, signed with the key provisioned through your developer account (see “Configure push notifications” in Xcode help). After you have this token, you can start to send push messages. You must then periodically update the token; each APNs provider authentication token has validity interval of one hour.

APNs allows multiple concurrent streams for each connection. The exact number of streams differs based on your use of a provider certificate or an authentication token, and also differs based on server load. Do not assume a specific number of streams.

When establishing a connection to APNs using a token rather than a certificate, only one stream is allowed on the connection until you send a push message with valid provider authentication token. APNs ignores HTTP/2 PRIORITY frames, so do not send them on your streams.

Best Practices for Managing Connections

Keep your connections with APNs open across multiple notifications; do not repeatedly open and close connections. APNs treats rapid connection and disconnection as a denial-of-service attack. You should leave a connection open unless you know it will be idle for an extended period of time—for example, if you only send notifications to your users once a day, it is acceptable practice to use a new connection each day.

Do not generate a new provider authentication token for each push request that you send. After you obtain a token, continue to use it for all your push requests during the token’s period of validity, which is one full hour.

You can establish multiple connections to APNs servers to improve performance. When you send a large number of remote notifications, distribute them across connections to several server endpoints. This improves performance, compared to using a single connection, by letting you send remote notifications faster and by letting APNs deliver them faster.

If your provider certificate is revoked, or if the key you are using to sign provider tokens is revoked, close all existing connections to APNs and then open new connections.

You can check the health of your connection using an HTTP/2 PING frame.

Terminating an APNs Connection

If APNs decides to terminate an established HTTP/2 connection, it sends a GOAWAY frame. The GOAWAY frame includes JSON data in its payload with a reason key, whose value indicates the reason for the connection termination. For a list of possible values for the reason key, see Table 8-6.

Normal request failures do not result in termination of a connection.

APNs Notification APIThe APNs Provider API consists of a request and a response that you configure and send using an HTTP/2 POST command. You use the request to send a push notification to the APNs server and use the response to determine the results of that request.

HTTP/2 Request to APNs

Use a request to send a notification to a specific user device.

Table 8-1HTTP/2 request fields

Name     |Value

:method |POST

:path      |/3/device/<device-token>

For the<device-token> parameter, specify the hexadecimal bytes of the device token for the target device.

APNs requires the use of HPACK (header compression for HTTP/2), which prevents repeated header keys and values. APNs maintains a small dynamic table for HPACK. To help avoid filling up the APNs HPACK table and necessitating the discarding of table data, encode headers in the following way—especially when sending a large number of streams:

The :path value should be encoded as a literal header field without indexing

The authorization request header, if present, should be encoded as a literal header field without indexing

The appropriate encoding to employ for the apns-id, apns-expiration, and apns-collapse-id request headers differs depending on whether it is part of the initial or a subsequent POST operation, as follows:

The first time you send these headers, encode them with incremental indexing to allow the header names to be added to the dynamic table

Subsequent times you send these headers, encode them as literal header fields without indexing

Encode all other headers as literal header fields with incremental indexing. For specifics on header encoding, see tools.ietf.org/html/rfc7541#section-6.2.1 and tools.ietf.org/html/rfc7541#section-6.2.2.

APNs ignores request headers other than the ones listed in Table 8-2.

Table 8-2APNs request headers

Header          |Description

authorization |The provider token that authorizes APNs to send push notifications for the specified topics. The token is in Base64URL-encoded JWT format, specified as bearer<provider token>.

                       |When the provider certificate is used to establish a connection, this request header is ignored.

apns-id         |A canonical UUID that identifies the notification. If there is an error sending the notification, APNs uses this value to identify the notification to your server.

                       |The canonical form is 32 lowercase hexadecimal digits, displayed in five groups separated by hyphens in the form 8-4-4-4-12. An example UUID is as follows:

                       |123e4567-e89b-12d3-a456-42665544000

                       |If you omit this header, a new UUID is created by APNs and returned in the response.

apns-expiration  | A UNIX epoch date expressed in seconds (UTC). This header identifies the date when the notification is no longer valid and can be discarded.If this value is nonzero, APNs stores the notification and tries to deliver it at least once, repeating the attempt as needed if it is unable to deliver the notification the first time. If the value is 0, APNs treats the notification as if it expires immediately and does not store the notification or attempt to redeliver it.

apns-priority  | The priority of the notification. Specify one of the following values:10–Send the push message immediately. Notifications with this priority must trigger an alert, sound, or badge on the target device. It is an error to use this priority for a push notification that contains only the content-available key.5—Send the push message at a time that takes into account power considerations for the device. Notifications with this priority might be grouped and delivered in bursts. They are throttled, and in some cases are not delivered.

                       | If you omit this header, the APNs server sets the priority to 10.

apns-topic    |The topic of the remote notification, which is typically the bundle ID for your app. The certificate you create in your developer account must include the capability for this topic.If your certificate includes multiple topics, you must specify a value for this header.If you omit this request header and your APNs certificate does not specify multiple topics, the APNs server uses the certificate’s Subject as the default topic.If you are using a provider token instead of a certificate, you must specify a value for this request header. The topic you provide should be provisioned for the your team named in your developer account.

apns-collapse-id  | Multiple notifications with the same collapse identifier are displayed to the user as a single notification. The value of this key must not exceed 64 bytes. For more information, see Quality of Service, Store-and-Forward, and Coalesced Notifications.


The body content of your message is the JSON dictionary object for your notification’s payload. The body data must not be compressed and its maximum size is 4KB (4096 bytes). For a Voice over Internet Protocol (VoIP) notification, the body data maximum size is 5KB (5120 bytes). For information about the keys and values to include in the body content, see Payload Key Reference.

HTTP/2 Response from APNs

The response to a request has the format listed in Table 8-3.

Table 8-3APNs response headers

Header name Value

apns-id  | The apns-id value from the request. If no value was included in the request, the server creates a new UUID and returns it in this header.

:status  | The HTTP status code. For a list of possible status codes, see Table 8-4.

Table 8-4 lists the possible status codes for a request. These values are included in the :status header of the response.

Table 8-4Status codes for an APNs responseStatus codeDescription200Success400Bad request403There was an error with the certificate or with the provider authentication token405The request used a bad :method value. Only POST requests are supported.410The device token is no longer active for the topic.413The notification payload was too large.429The server received too many requests for the same device token.500Internal server error503The server is shutting down and unavailable.

For a successful request, the body of the response is empty. On failure, the response body contains a JSON dictionary with the keys listed in Table 8-5. This JSON data might also be included in the GOAWAY frame when a connection is terminated.Table 8-5APNs JSON data keysKeyDescriptionreasonThe error indicating the reason for the failure. The error code is specified as a string.

 For a list of possible values, see Table 8-6.timestampIf the value in the :status header is 410, the value of this key is the last time at which APNs confirmed that the device token was no longer valid for the topic.Stop pushing notifications until the device registers a token with a later timestamp with your provider.Table 8-6 lists the possible error codes included in the reason key of a response’s JSON payload.Table 8-6Values for the APNs JSON reason keyStatus codeError stringDescription400BadCollapseIdThe collapse identifier exceeds the maximum allowed size400BadDeviceTokenThe specified device token was bad. Verify that the request contains a valid token and that the token matches the environment.400BadExpirationDateThe apns-expiration value is bad.400BadMessageIdThe apns-id value is bad.400BadPriorityThe apns-priority value is bad.400BadTopicThe apns-topic was invalid.400DeviceTokenNotForTopicThe device token does not match the specified topic.400DuplicateHeadersOne or more headers were repeated.400IdleTimeoutIdle time out.400MissingDeviceTokenThe device token is not specified in the request :path. Verify that the :path header contains the device token.400MissingTopicThe apns-topic header of the request was not specified and was required. The apns-topic header is mandatory when the client is connected using a certificate that supports multiple topics.400PayloadEmptyThe message payload was empty.400TopicDisallowedPushing to this topic is not allowed.403BadCertificateThe certificate was bad.403BadCertificateEnvironmentThe client certificate was for the wrong environment.403ExpiredProviderTokenThe provider token is stale and a new token should be generated.403ForbiddenThe specified action is not allowed.403InvalidProviderTokenThe provider token is not valid or the token signature could not be verified.403MissingProviderTokenNo provider certificate was used to connect to APNs and Authorization header was missing or no provider token was specified.404BadPathThe request contained a bad :path value.405MethodNotAllowedThe specified :method was not POST.410UnregisteredThe device token is inactive for the specified topic.Expected HTTP/2 status code is 410; see Table 8-4.413PayloadTooLargeThe message payload was too large. See Creating the Remote Notification Payload for details on maximum payload size.429TooManyProviderTokenUpdatesThe provider token is being updated too often.429TooManyRequestsToo many requests were made consecutively to the same device token.500InternalServerErrorAn internal server error occurred.503ServiceUnavailableThe service is unavailable.503ShutdownThe server is shutting down.

HTTP/2 Request/Response Examples for APNs

Listing 8-1 shows a sample request constructed for a provider certificate.Listing 8-1Sample request for a certificate with a single topicHEADERS  - END_STREAM  + END_HEADERS  :method = POST  :scheme = https  :path = /3/device/00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0  host = api.development.push.apple.com  apns-id = eabeae54-14a8-11e5-b60b-1697f925ec7b  apns-expiration = 0  apns-priority = 10DATA  + END_STREAM    { "aps" : { "alert" : "Hello" } }

Listing 8-2 shows a sample request constructed for a provider authentication token.Listing 8-2Sample request for a provider authentication tokenHEADERS  - END_STREAM  + END_HEADERS  :method = POST  :scheme = https  :path = /3/device/00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0  host = api.development.push.apple.com  authorization = bearer eyAia2lkIjogIjhZTDNHM1JSWDciIH0.eyAiaXNzIjogIkM4Nk5WOUpYM0QiLCAiaWF0I jogIjE0NTkxNDM1ODA2NTAiIH0.MEYCIQDzqyahmH1rz1s-LFNkylXEa2lZ_aOCX4daxxTZkVEGzwIhALvkClnx5m5eAT6 Lxw7LZtEQcH6JENhJTMArwLf3sXwi  apns-id = eabeae54-14a8-11e5-b60b-1697f925ec7b  apns-expiration = 0  apns-priority = 10  apns-topic =DATA  + END_STREAM    { "aps" : { "alert" : "Hello" } }Listing 8-3 shows a sample request constructed for a certificate that contains multiple topics.

Listing 8-3Sample request for a certificate with multiple topicsHEADERS  - END_STREAM  + END_HEADERS  :method = POST  :scheme = https  :path = /3/device/00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0  host = api.development.push.apple.com  apns-id = eabeae54-14a8-11e5-b60b-1697f925ec7b  apns-expiration = 0  apns-priority = 10  apns-topic =DATA  + END_STREAM    { "aps" : { "alert" : "Hello" } }

Listing 8-4 shows a sample response for a successful push request.Listing 8-4Sample response for a successful requestHEADERS  + END_STREAM  + END_HEADERS  apns-id = eabeae54-14a8-11e5-b60b-1697f925ec7b  :status = 200

Listing 8-5 shows a sample response when an error occurs.Listing 8-5Sample response for a request that encountered an errorHEADERS  - END_STREAM  + END_HEADERS  :status = 400  content-type = application/json    apns-id:DATA

+ END_STREAM

{ "reason" : "BadDeviceToken" }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容