Join us for Firebase Summit on November 10, 2021. Tune in to learn how Firebase can help you accelerate app development, release with confidence, and scale with ease. Register

在 iOS 上使用 App Check 保護非 Firebase 資源

您可以使用 App Check 保護應用的非 Firebase 資源,例如自託管後端。為此,您需要執行以下兩項操作:

  • 修改您的應用程序客戶端以將 App Check 令牌與每個請求一起發送到您的後端,如本頁所述。
  • 修改後端需要一個有效的應用程序令牌檢查每個請求,如在從定制後端驗證應用程序檢查令牌

在你開始之前

添加應用程序檢查到您的應用程序,即使用應用程序的AttestDeviceCheck ,或自定義提供

使用後端請求發送 App Check 令牌

為了確保您的後端請求包含一個有效的,未過期的,應用程序檢查令牌,在呼叫包裝每個請求AppCheck.token() App Check 庫會在必要時刷新令牌,您可以在方法的完成塊中訪問令牌。

獲得有效令牌後,將其與請求一起發送到後端。你是如何做到這一點的細節是你的,但不發送應用程序檢查令牌作為網址的一部分,包括在查詢參數,因為這使得他們很容易受到意外洩漏和攔截。以下示例在自定義 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];
}];