使用 App Check 保护自定义后端资源(Apple 平台)
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
您可以使用 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) {
// ...
}];
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-23。
[null,null,["最后更新时间 (UTC):2025-08-23。"],[],[],null,["You 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\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\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\nSwift \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\nObjective-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\nReplay 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\nSwift \n\n AppCheck.appCheck().limitedUseToken() { token, error in\n // ...\n }\n\nObjective-C \n\n [[FIRAppCheck appCheck] limitedUseTokenWithCompletion:^(FIRAppCheckToken * _Nullable token,\n NSError * _Nullable error) {\n // ...\n }];"]]