Cloud Functions의 앱 체크 적용 사용 설정

앱 체크가 사용자에게 미치는 영향을 이해하고 계속 진행할 준비가 되면 앱 체크 적용을 사용 설정할 수 있습니다.

적용 사용 설정

호출 가능한 Cloud Functions에서 앱 체크 토큰 요구사항을 적용하려면 함수를 수정하여 아래와 같이 유효한 앱 체크 토큰이 있는지 확인하세요. 적용을 사용 설정하면 확인되지 않은 모든 요청이 거부됩니다.

  1. Cloud Functions SDK를 설치합니다.

    Node.js(1세대)

    프로젝트의 firebase-functions 종속 항목을 버전 4.0.0 이상으로 업데이트합니다.

    npm install firebase-functions@">=4.0.0"
    

    Node.js(2세대)

    프로젝트의 firebase-functions 종속 항목을 버전 4.0.0 이상으로 업데이트합니다.

    npm install firebase-functions@">=4.0.0"
    

    Python(미리보기)

    firebase-functionsfunctions/requirements.txt에 추가합니다.

    firebase-functions >= 0.1.0
    

    그런 다음 프로젝트의 가상 환경에서 종속 항목을 업데이트합니다.

    ./venv/bin/pip install -r requirements.txt
    
  2. 함수에 앱 체크 적용 런타임 옵션을 사용 설정합니다.

    Node.js(1세대)

    const functions = require("firebase-functions/v1");
    
    exports.yourV1CallableFunction = functions
      .runWith({
          enforceAppCheck: true, // Reject requests with missing or invalid App Check tokens.
      })
      .https.onCall((data, context) => {
            // context.app contains data from App Check, including the app ID.
            // Your function logic follows.
            ...
      });
    

    Node.js(2세대)

    const { onCall } = require("firebase-functions/v2/https");
    
    exports.yourV2CallableFunction = onCall(
      {
        enforceAppCheck: true, // Reject requests with missing or invalid App Check tokens.
      },
      (request) => {
        // request.app contains data from App Check, including the app ID.
        // Your function logic follows.
        ...
      }
    );
    

    Python(미리보기)

    from firebase_functions import https_fn
    
    @https_fn.on_call(
        enforce_app_check=True  # Reject requests with missing or invalid App Check tokens.
    )
    def your_callable_function(req: https_fn.CallableRequest) -> https_fn.Response:
        # req.app contains data from App Check, including the app ID.
        # Your function logic follows.
        ...
    
  3. 함수를 다시 배포합니다.

    firebase deploy --only functions
    

이러한 변경사항이 배포되면 호출 가능한 Cloud Functions에 유효한 앱 체크 토큰이 필요합니다. Cloud Functions 클라이언트 SDK는 호출 가능 함수를 호출할 때 앱 체크 토큰을 자동으로 연결합니다.

재생 보호(베타)

호출 가능 함수를 재생 공격으로부터 보호하려면 앱 체크 토큰을 확인한 후에 소비하면 됩니다. 한 번 소비된 토큰은 다시 사용할 수 없습니다.

재생 보호 기능을 사용하면 토큰 확인에 대한 네트워크 왕복이 추가되어 Cloud 함수 호출에 지연 시간이 추가됩니다. 따라서 대부분의 앱은 일반적으로 특히 민감한 엔드포인트에서만 재생 보호를 사용 설정합니다.

토큰을 소비하려면 다음 안내를 따르세요.

  1. Cloud 콘솔에서 Cloud 함수에서 사용하는 서비스 계정에 'Firebase 앱 체크 토큰 확인자' 역할을 부여합니다.

    • Admin SDK를 명시적으로 초기화하고 프로젝트의 Admin SDK 서비스 계정 사용자 인증 정보를 지정한 경우 필수 역할이 이미 부여된 것입니다.
    • 1세대 Cloud Functions를 기본 Admin SDK 구성과 함께 사용하는 경우 App Engine 기본 서비스 계정에 역할을 부여합니다. 서비스 계정 권한 변경을 참조하세요.
    • 2세대 Cloud Functions를 기본 Admin SDK 구성과 함께 사용하는 경우 기본 컴퓨팅 서비스 계정에 역할을 부여합니다.
  2. 함수 정의에서 consumeAppCheckTokentrue로 설정합니다.

    Node.js(1세대)

    const functions = require("firebase-functions/v1");
    
    exports.yourV1CallableFunction = functions
      .runWith({
          enforceAppCheck: true, // Reject requests with missing or invalid App Check tokens.
          consumeAppCheckToken: true  // Consume the token after verification.
      })
      .https.onCall((data, context) => {
          // context.app contains data from App Check, including the app ID.
          // Your function logic follows.
          ...
      });
    

    Node.js(2세대)

    const { onCall } = require("firebase-functions/v2/https");
    
    exports.yourV2CallableFunction = onCall(
      {
        enforceAppCheck: true, // Reject requests with missing or invalid App Check tokens.
        consumeAppCheckToken: true  // Consume the token after verification.
      },
      (request) => {
        // request.app contains data from App Check, including the app ID.
        // Your function logic follows.
        ...
      }
    );
    
  3. 앱 클라이언트 코드를 업데이트하여 함수를 호출할 때 사용 빈도가 제한된 소모성 토큰을 얻어야 합니다.

    Swift

    let options = HTTPSCallableOptions(requireLimitedUseAppCheckTokens: true)
    let yourCallableFunction =
        Functions.functions().httpsCallable("yourCallableFunction", options: options)
    do {
        let result = try await yourCallableFunction.call()
    } catch {
        // ...
    }
    

    웹 모듈식 API

    import { getFunctions, httpsCallable } from "firebase/functions";
    
    const yourCallableFunction = httpsCallable(
      getFunctions(),
      "yourCallableFunction",
      { limitedUseAppCheckTokens: true },
    );
    await yourCallableFunction();
    

    Kotlin+KTX

    val yourCallableFunction = Firebase.functions.getHttpsCallable("yourCallableFunction") {
        limitedUseAppCheckTokens = true
    }
    val result = yourCallableFunction.call().await()
    

    Java

    HttpsCallableReference yourCallableFunction = FirebaseFunctions.getInstance().getHttpsCallable(
            "yourCallableFunction",
            new HttpsCallableOptions.Builder()
                    .setLimitedUseAppCheckTokens(true)
                    .build()
    );
    Task<HttpsCallableResult> result = yourCallableFunction.call();