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];
}];