在 Apple 平台上使用 App Check 保護自訂後端資源
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
您可以透過 App Check 保護應用程式的非 Google 自訂後端資源,例如自行管理的後端。如要這麼做,請完成下列兩項操作:
- 如本頁所述,修改應用程式用戶端,在每次傳送至後端的要求中加入 App Check 權杖。
- 修改後端,要求每個要求都附上有效的 App Check 權杖,詳情請參閱「從自訂後端驗證 App Check 權杖」。
事前準備
使用 App Attest、DeviceCheck 或自訂供應商,將 App Check 新增至應用程式。
在後端要求中傳送 App Check 權杖
為確保後端要求包含有效且未過期的 App Check 權杖,請在對 AppCheck.token()
的呼叫中包裝每個要求。如有必要,App Check 程式庫會重新整理權杖,您可以在方法的完成區塊中存取權杖。
取得有效權杖後,請將權杖連同要求傳送至後端。具體做法由您決定,但請勿將 App Check 權杖做為網址的一部分傳送 (包括查詢參數),否則權杖可能會意外洩漏或遭到攔截。下列範例會在自訂 HTTP 標頭中傳送權杖,這是建議的做法。
Swift
do {
let token = try await AppCheck.appCheck().token(forcingRefresh: false)
// Get the raw App Check token string.
let tokenString = token.token
// Include the App Check token with requests to your server.
let url = URL(string: "https://yourbackend.example.com/yourApiEndpoint")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue(tokenString, forHTTPHeaderField: "X-Firebase-AppCheck")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
// Handle response from your backend.
}
task.resume()
} catch(let error) {
print("Unable to retrieve App Check token: \(error)")
return
}
Objective-C
[[FIRAppCheck appCheck] tokenForcingRefresh:NO
completion:^(FIRAppCheckToken * _Nullable token,
NSError * _Nullable error) {
if (error != nil) {
// Handle any errors if the token was not retrieved.
NSLog(@"Unable to retrieve App Check token: %@", error);
return;
}
if (token == nil) {
NSLog(@"Unable to retrieve App Check token.");
return;
}
// Get the raw App Check token string.
NSString *tokenString = token.token;
// Include the App Check token with requests to your server.
NSURL *url = [[NSURL alloc] initWithString:@"https://yourbackend.example.com/yourApiEndpoint"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"GET"];
[request setValue:tokenString forHTTPHeaderField:@"X-Firebase-AppCheck"];
NSURLSessionDataTask *task =
[[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data,
NSURLResponse * _Nullable response,
NSError * _Nullable error) {
// Handle response from your backend.
}];
[task resume];
}];
重送攻擊防護 (Beta 版)
向已啟用重播保護機制的端點提出要求時,請將要求包裝在 limitedUseToken()
的呼叫中,而非 token()
:
Swift
AppCheck.appCheck().limitedUseToken() { token, error in
// ...
}
Objective-C
[[FIRAppCheck appCheck] limitedUseTokenWithCompletion:^(FIRAppCheckToken * _Nullable token,
NSError * _Nullable error) {
// ...
}];
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-23 (世界標準時間)。
[null,null,["上次更新時間:2025-08-23 (世界標準時間)。"],[],[],null,["# Protect custom backend resources with App Check on Apple platforms\n\nYou can use App Check to protect non-Google custom backend resources for\nyour app, like your own self-hosted backend. To do so, you'll need to do both of\nthe following:\n\n- Modify your app client to send an App Check token along with each request to your backend, as described on this page.\n- Modify your backend to require a valid App Check token with every request, as described in [Verify App Check tokens from a custom backend](/docs/app-check/custom-resource-backend).\n\nBefore you begin\n----------------\n\nAdd App Check to your app, using either [App Attest](/docs/app-check/ios/app-attest-provider),\n[DeviceCheck](/docs/app-check/ios/devicecheck-provider), or a [custom provider](/docs/app-check/ios/custom-provider).\n\nSend App Check tokens with backend requests\n-------------------------------------------\n\nTo ensure your backend requests include a valid, unexpired, App Check token,\nwrap each request in a call to `AppCheck.token()`. The App Check library\nwill refresh the token if necessary, and you can access the token in the\nmethod's completion block.\n\nOnce you have a valid token, send it along with the request to your backend. The\nspecifics of how you accomplish this are up to you, but *don't send\nApp Check tokens as part of URLs*, including in query parameters, as this\nmakes them vulnerable to accidental leakage and interception. The following\nexample sends the token in a custom HTTP header, which is the recommended\napproach. \n\n### Swift\n\n```swift\ndo {\n let token = try await AppCheck.appCheck().token(forcingRefresh: false)\n\n // Get the raw App Check token string.\n let tokenString = token.token\n\n // Include the App Check token with requests to your server.\n let url = URL(string: \"https://yourbackend.example.com/yourApiEndpoint\")!\n var request = URLRequest(url: url)\n request.httpMethod = \"GET\"\n request.setValue(tokenString, forHTTPHeaderField: \"X-Firebase-AppCheck\")\n\n let task = URLSession.shared.dataTask(with: request) { data, response, error in\n // Handle response from your backend.\n }\n task.resume()\n} catch(let error) {\n print(\"Unable to retrieve App Check token: \\(error)\")\n return\n}\n```\n\n### Objective-C\n\n```objective-c\n[[FIRAppCheck appCheck] tokenForcingRefresh:NO\n completion:^(FIRAppCheckToken * _Nullable token,\n NSError * _Nullable error) {\n if (error != nil) {\n // Handle any errors if the token was not retrieved.\n NSLog(@\"Unable to retrieve App Check token: %@\", error);\n return;\n }\n if (token == nil) {\n NSLog(@\"Unable to retrieve App Check token.\");\n return;\n }\n\n // Get the raw App Check token string.\n NSString *tokenString = token.token;\n\n // Include the App Check token with requests to your server.\n NSURL *url = [[NSURL alloc] initWithString:@\"https://yourbackend.example.com/yourApiEndpoint\"];\n NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];\n [request setHTTPMethod:@\"GET\"];\n [request setValue:tokenString forHTTPHeaderField:@\"X-Firebase-AppCheck\"];\n\n NSURLSessionDataTask *task =\n [[NSURLSession sharedSession] dataTaskWithRequest:request\n completionHandler:^(NSData * _Nullable data,\n NSURLResponse * _Nullable response,\n NSError * _Nullable error) {\n // Handle response from your backend.\n }];\n [task resume];\n}];\n```\n\n### Replay protection (beta)\n\nWhen making a request to an endpoint for which you've enabled\n[replay protection](/docs/app-check/custom-resource-backend#replay-protection),\nwrap the request in a call to `limitedUseToken()` instead of `token()`: \n\n### Swift\n\n AppCheck.appCheck().limitedUseToken() { token, error in\n // ...\n }\n\n### Objective-C\n\n [[FIRAppCheck appCheck] limitedUseTokenWithCompletion:^(FIRAppCheckToken * _Nullable token,\n NSError * _Nullable error) {\n // ...\n }];"]]