您可以使用 App Check 保护应用的非 Firebase 资源,例如自托管后端。为此,您需要执行以下两项操作:
- 修改您的应用程序客户端以将 App Check 令牌与每个请求一起发送到您的后端,如本页所述。
- 修改您的后端以在每个请求中都需要有效的 App Check 令牌,如从自定义后端验证 App Check 令牌中所述。
在你开始之前
使用App Attest 、 DeviceCheck或自定义提供程序将 App Check 添加到您的应用程序。
使用后端请求发送 App Check 令牌
为确保您的后端请求包含有效、未过期的 App Check 令牌,请将每个请求包装在对AppCheck.token()
的调用中。 App Check 库将在必要时刷新令牌,您可以在方法的完成块中访问令牌。
获得有效令牌后,将其与请求一起发送到后端。具体如何实现由您决定,但不要将 App Check 令牌作为 URL 的一部分发送,包括在查询参数中,因为这会使它们容易受到意外泄漏和拦截。以下示例在自定义 HTTP 标头中发送令牌,这是推荐的方法。
迅速
AppCheck.appCheck().token(forcingRefresh: false) { token, error in guard error == nil else { // Handle any errors if the token was not retrieved. print("Unable to retrieve App Check token: \(error!)") return } guard let token = token else { print("Unable to retrieve App Check token.") return } // 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() }
目标-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]; }];