Enable App Check with a custom provider on Android

This page shows you how to enable App Check in an Android app, using your custom App Check provider. When you enable App Check, you help ensure that only your app can access your project's Firebase resources.

If you want to use App Check with the default SafetyNet provider, see Enable App Check with SafetyNet on Android.

Before you begin

1. Add the App Check library to your app

In your module (app-level) Gradle file (usually app/build.gradle), declare the dependency for the App Check Android library:

Java

dependencies {
    implementation 'com.google.firebase:firebase-appcheck:16.0.0-beta02'
}

Kotlin+KTX

dependencies {
    implementation 'com.google.firebase:firebase-appcheck:16.0.0-beta02'
}

2. Implement the App Check interfaces

First, you need to create classes that implement the AppCheckProvider and AppCheckProviderFactory interfaces.

Your AppCheckProvider class must have a getToken() method, which collects whatever information your custom App Check provider requires as proof of authenticity, and sends it to your token acquisition service in exchange for an App Check token. The App Check SDK handles token caching, so always get a new token in your implementation of getToken().

Java

public class YourCustomAppCheckToken extends AppCheckToken {
    private String token;
    private long expiration;

    YourCustomAppCheckToken(String token, long expiration) {
        this.token = token;
        this.expiration = expiration;
    }

    @NonNull
    @Override
    public String getToken() {
        return token;
    }

    @Override
    public long getExpireTimeMillis() {
        return expiration;
    }
}

public class YourCustomAppCheckProvider implements AppCheckProvider {
    @Override
    public Task<AppCheckToken> getToken() {
        // Logic to exchange proof of authenticity for an App Check token and
        //   expiration time.
        // ...

        // Refresh the token early to handle clock skew.
        long expMillis = expirationFromServer * 1000 - 60000;

        // Create AppCheckToken object.
        AppCheckToken appCheckToken =
                YourCustomAppCheckToken(tokenFromServer, expMillis);

        return appCheckToken;
    }
}

Kotlin+KTX

class YourCustomAppCheckToken(
    private val token: String,
    private val expiration: Long
) : AppCheckToken() {
    override fun getToken(): String {
        return token
    }

    override fun getExpireTimeMillis(): Long {
        return expiration
    }
}

class YourCustomAppCheckProvider : AppCheckProvider {
    val token: Task<AppCheckToken>
        get() {
            // Logic to exchange proof of authenticity for an App Check token.
            // ...

            // Refresh the token early to handle clock skew.
            val expMillis: Long = expirationFromServer * 1000 - 60000

            // Create AppCheckToken object.
            val appCheckToken: AppCheckToken =
                    YourCustomAppCheckToken(tokenFromServer, expMillis)

            return appCheckToken!
        }
}

Also, implement a AppCheckProviderFactory class that creates instances of your AppCheckProvider implementation:

Java

public class YourCustomAppCheckProviderFactory implements AppCheckProviderFactory {
  @Override
  public AppCheckProvider create(FirebaseApp firebaseApp) {
    // Create and return an AppCheckProvider object.
    return new YourCustomAppCheckProvider(firebaseApp);
  }
}

Kotlin+KTX

class YourCustomAppCheckProviderFactory : AppCheckProviderFactory {
    fun create(firebaseApp: FirebaseApp): AppCheckProvider {
        // Create and return an AppCheckProvider object.
        return YourCustomAppCheckProvider(firebaseApp)
    }
}

3. Initialize App Check

Add the following initialization code to your app so that it runs before you use any other Firebase SDKs:

Java

FirebaseApp.initializeApp(/*context=*/ this);
FirebaseAppCheck firebaseAppCheck = FirebaseAppCheck.getInstance();
firebaseAppCheck.installAppCheckProviderFactory(
    YourCustomAppCheckProviderFactory.getInstance());

Kotlin+KTX

FirebaseApp.initializeApp(/*context=*/ this)
val firebaseAppCheck = FirebaseAppCheck.getInstance()
firebaseAppCheck.installAppCheckProviderFactory(
    YourCustomAppCheckProviderFactory.getInstance())

Once the App Check library is installed in your app, start distributing the updated app to your users.

The updated client app will begin sending App Check tokens along with every request it makes to Firebase, but Firebase products will not require the tokens to be valid until you enable enforcement in the App Check section of the Firebase console. See the next two sections for details.

4. Monitor request metrics

Now that your updated app is in the hands of users, you can enable enforcement of App Check for the Firebase products you use. Before you do so, however, you should make sure that doing so won’t disrupt your existing legitimate users.

Realtime Database and Cloud Storage

An important tool you can use to make this decision for Realtime Database and Cloud Storage is the App Check request metrics screen.

To view the App Check request metrics for a product, open the Project Settings > App Check section of the Firebase console. For example:

Screenshot of the App Check metrics page

The request metrics for each product are broken down into four categories:

  • Verified requests are those that have a valid App Check token. After you enable App Check enforcement, only requests in this category will succeed.

  • Outdated client requests are those that are missing an App Check token. These requests might be from an older version of the Firebase SDK before App Check was included in the app.

  • Unknown origin requests are those that are missing an App Check token, and don't look like they come from the Firebase SDK. These might be from requests made with stolen API keys or forged requests made without the Firebase SDK.

  • Invalid requests are those that have an invalid App Check token, which might be from an inauthentic client attempting to impersonate your app, or from emulated environments.

The distribution of these categories for your app should inform when you decide to enable enforcement. Here are some guidelines:

  • If almost all of the recent requests are from verified clients, consider enabling enforcement to start protecting your backend resources.

  • If a significant portion of the recent requests are from likely-outdated clients, to avoid disrupting users, consider waiting for more users to update your app before enabling enforcement. Enforcing App Check on a released app will break prior app versions that are not integrated with the App Check SDK.

  • If your app hasn't launched yet, you should enable App Check enforcement immediately, since there aren't any outdated clients in use.

Cloud Functions

For Cloud Functions, you can get App Check metrics by examining your functions' logs. Every invocation of a callable function emits a structured log entry like the following example:

{
  "severity": "INFO",    // INFO, WARNING, or ERROR
  "logging.googleapis.com/labels": {"firebase-log-type": "callable-request-verification"},
  "jsonPayload": {
    "message": "Callable header verifications passed.",
    "verifications": {
      // ...
      "app": "MISSING",  // VALID, INVALID, or MISSING
    }
  }
}

You can analyze these metrics in the Google Cloud Console by creating a logs-based counter metric with the following metric filter:

resource.type="cloud_function"
resource.labels.function_name="YOUR_CLOUD_FUNCTION"
resource.labels.region="us-central1"
labels.firebase-log-type="callable-request-verification"

Label the metric using the field jsonPayload.verifications.appCheck.

5. Enable enforcement

To enable enforcement, follow the instructions for each product, below. Once you enable enforcement for a product, all unverified requests to that product will be rejected.

Realtime Database and Cloud Storage

To enable enforcement for Realtime Database and Cloud Storage:

  1. Open the Project Settings > App Check section of the Firebase console.

  2. Expand the metrics view of the product for which you want to enable enforcement.

  3. Click Enforce and confirm your choice.

Note that it can take up to 10 minutes after you enable enforcement for it to take effect.

Cloud Functions

See Enable App Check enforcement for Cloud Functions.