Skip to content

Commit 7181d53

Browse files
App Check docs from firebase.google.com (#8101)
1 parent cac41fb commit 7181d53

File tree

5 files changed

+281
-110
lines changed

5 files changed

+281
-110
lines changed

docs/app-check/custom-resource.mdx

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
---
2+
title: Protect non-Firebase resources with App Check
3+
sidebar_label: Non-Firebase resources
4+
---
5+
6+
You can protect your app's non-Firebase resources, such as self-hosted backends,
7+
with App Check. To do so, you will need to do both of the following:
8+
9+
- Modify your app client to send an App Check token along with each request
10+
to your backend, as described on this page.
11+
- Modify your backend to require a valid App Check token with every request,
12+
as described in [Verify App Check tokens from a custom backend](https://firebase.google.com/docs/app-check/custom-resource-backend).
13+
14+
## Before you begin
15+
16+
Add App Check to your app, using the [default providers](default-providers).
17+
18+
## Send App Check tokens with backend requests
19+
20+
To ensure your backend requests include a valid, unexpired, App Check token,
21+
precede each request with a call to `getToken()`. The App Check library
22+
will refresh the token if necessary.
23+
24+
Once you have a valid token, send it along with the request to your backend. The
25+
specifics of how you accomplish this are up to you, but _don't send
26+
App Check tokens as part of URLs_, including in query parameters, as this
27+
makes them vulnerable to accidental leakage and interception. The recommended
28+
approach is to send the token in a custom HTTP header.
29+
30+
For example:
31+
32+
```dart
33+
void callApiExample() async {
34+
final appCheckToken = await FirebaseAppCheck.instance.getToken();
35+
if (appCheckToken != null) {
36+
final response = await http.get(
37+
Uri.parse("https://yourbackend.example.com/yourExampleEndpoint"),
38+
headers: {"X-Firebase-AppCheck": appCheckToken},
39+
);
40+
} else {
41+
// Error: couldn't get an App Check token.
42+
}
43+
}
44+
```

docs/app-check/usage.mdx renamed to docs/app-check/debug-provider.mdx

Lines changed: 6 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -1,94 +1,17 @@
11
---
2-
title: App Check
3-
sidebar_label: Usage
2+
title: Use App Check with the debug provider
3+
sidebar_label: Debugging
44
---
55

6-
Once installed, you can access the [`firebase_app_check`](!firebase_app_check) plugin by importing
7-
it in your Dart code:
8-
9-
```dart
10-
import 'package:firebase_app_check/firebase_app_check.dart';
11-
```
12-
13-
To create a new Firebase App Check instance, call the instance getter on `FirebaseAppCheck`:
14-
15-
```dart
16-
FirebaseAppCheck appCheck = FirebaseAppCheck.instance;
17-
```
18-
19-
By default, this allows you to interact with Firebase App Check using the default Firebase App used whilst installing FlutterFire on your platform. If however you'd like to use a secondary Firebase App, use the `instanceFor` method:
20-
21-
```dart
22-
FirebaseApp secondaryApp = Firebase.app('SecondaryApp');
23-
FirebaseAppCheck appCheck = FirebaseAppCheck.instanceFor(app: secondaryApp);
24-
```
25-
26-
## Activate the default provider
27-
28-
To activate the default App Check attestation provider you must call activate before any usages of your Firebase
29-
services such as Storage, but after calling `Firebase.initializeApp()`;
30-
31-
```dart {10} title="lib/main.dart"
32-
import 'package:flutter/material.dart';
33-
import 'package:firebase_core/firebase_core.dart';
34-
35-
// Import the firebase_app_check plugin
36-
import 'package:firebase_app_check/firebase_app_check.dart';
37-
38-
Future<void> main() async {
39-
WidgetsFlutterBinding.ensureInitialized();
40-
await Firebase.initializeApp();
41-
await FirebaseAppCheck.instance.activate(
42-
webRecaptchaSiteKey: 'recaptcha-v3-site-key',
43-
);
44-
runApp(App());
45-
}
46-
```
47-
48-
## Getting the current token
49-
50-
To get the current token associated with App Check, call the `getToken` method:
51-
52-
```dart
53-
String? token = await FirebaseAppCheck.instance.getToken();
54-
print(token);
55-
```
56-
57-
Optionally, you can force the token to refresh when fetching:
58-
59-
```dart
60-
String? token = await FirebaseAppCheck.instance.getToken(true);
61-
```
62-
63-
## Listen to token changes
64-
65-
To subscribe to App Check token changes, listen to the `onTokenChange` `Stream`:
66-
67-
```dart
68-
FirebaseAppCheck.instance.onTokenChange.listen((token) {
69-
print(token);
70-
});
71-
```
72-
73-
## Automatic refreshing
74-
75-
To enable the SDK to automatically refresh the App Check token when required, call the `setTokenAutoRefreshEnabled` method:
76-
77-
```dart
78-
await FirebaseAppCheck.instance.setTokenAutoRefreshEnabled(true);
79-
```
80-
81-
## Debugging
82-
83-
:::caution
84-
Warning: The debug provider allows access to your Firebase resources from unverified devices. Don't use the debug provider in production builds of your app, and don't share your debug builds with untrusted parties.
85-
:::
86-
876
If, after you have registered your app for App Check, and you want to run your app in an environment that
887
App Check would normally not classify as valid, such as a simulator during development, or from a continuous
898
integration (CI) environment, you can create a debug build of your app that uses the App Check debug provider instead
909
of a real attestation provider.
9110

11+
:::caution
12+
Warning: The debug provider allows access to your Firebase resources from unverified devices. Don't use the debug provider in production builds of your app, and don't share your debug builds with untrusted parties.
13+
:::
14+
9215
For now the debug provider does not currently have a Dart API; you'll need to apply the changes for your platforms as
9316
shown below:
9417

docs/app-check/default-providers.mdx

Lines changed: 220 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,220 @@
1+
---
2+
title: Enable App Check in Flutter apps
3+
sidebar_label: Enable App Check
4+
---
5+
6+
This page shows you how to enable App Check in a Flutter app, using the
7+
default providers: SafetyNet on Android, Device Check on Apple platforms, and
8+
reCAPTCHA v3 on web. When you enable App Check, you help ensure that
9+
only your app can access your project's Firebase resources. See an
10+
[Overview](overview) of this feature.
11+
12+
13+
## 1. Set up your Firebase project {#project-setup}
14+
15+
1. [Install and initialize FlutterFire](../overview) if you haven't
16+
already done so.
17+
18+
1. Register your apps to use App Check with the SafetyNet, Device Check, and reCAPTCHA providers in the
19+
[**Project Settings > App Check**](https://console.firebase.google.com/project/_/settings/appcheck)
20+
section of the Firebase console.
21+
22+
You usually need to register all of your project's apps, because once you
23+
enable enforcement for a Firebase product, only registered apps will be able
24+
to access the product's backend resources.
25+
26+
1. **Optional**: In the app registration settings, set a custom time-to-live
27+
(TTL) for App Check tokens issued by the provider. You can set the TTL
28+
to any value between 30 minutes and 7 days. When changing this value, be
29+
aware of the following tradeoffs:
30+
31+
- Security: Shorter TTLs provide stronger security, because it reduces the
32+
window in which a leaked or intercepted token can be abused by an
33+
attacker.
34+
- Performance: Shorter TTLs mean your app will perform attestation more
35+
frequently. Because the app attestation process adds latency to network
36+
requests every time it's performed, a short TTL can impact the performance
37+
of your app.
38+
- Quota and cost: Shorter TTLs and frequent re-attestation deplete your
39+
quota faster, and for paid services, potentially cost more.
40+
See [Quotas &amp; limits](https://firebase.google.com/docs/app-check#quotas_limits).
41+
42+
The default TTL
43+
is reasonable for most apps. Note that the App Check library refreshes
44+
tokens at approximately half the TTL duration.
45+
46+
47+
## 2. Add the App Check library to your app {#install-sdk}
48+
49+
1. From the root of your Flutter project, run the following command to install the plugin:
50+
51+
```bash
52+
flutter pub add firebase_app_check
53+
```
54+
55+
1. Once complete, rebuild your Flutter application:
56+
57+
```bash
58+
flutter run
59+
```
60+
61+
62+
## 3. Initialize App Check {#initialize}
63+
64+
Add the following initialization code to your app so that it runs before you
65+
use any Firebase services such as Storage, but after calling
66+
`Firebase.initializeApp()`;
67+
68+
```dart
69+
import 'package:flutter/material.dart';
70+
import 'package:firebase_core/firebase_core.dart';
71+
72+
// Import the firebase_app_check plugin
73+
import 'package:firebase_app_check/firebase_app_check.dart';
74+
75+
Future<void> main() async {
76+
WidgetsFlutterBinding.ensureInitialized();
77+
await Firebase.initializeApp();
78+
await FirebaseAppCheck.instance.activate(
79+
webRecaptchaSiteKey: 'recaptcha-v3-site-key',
80+
);
81+
runApp(App());
82+
}
83+
```
84+
85+
Once the App Check library is installed in your app, start distributing the
86+
updated app to your users.
87+
88+
The updated client app will begin sending App Check tokens along with every
89+
request it makes to Firebase, but Firebase products will not require the tokens
90+
to be valid until you enable enforcement in the App Check section of the
91+
Firebase console. See the next two sections for details.
92+
93+
94+
## 4. Monitor request metrics {#metrics}
95+
96+
Now that your updated app is in the hands of users, you can enable enforcement
97+
of App Check for the Firebase products you use. Before you do so, however,
98+
you should make sure that doing so won’t disrupt your existing legitimate users.
99+
100+
### Realtime Database, Cloud Firestore, and Cloud Storage {#metrics-other}
101+
102+
An important tool you can use to make this decision for Realtime Database,
103+
Cloud Firestore, and Cloud Storage is the App Check request metrics screen.
104+
105+
To view the App Check request metrics for a product, open the
106+
[**Project Settings > App Check**](https://console.firebase.google.com/project/_/settings/appcheck)
107+
section of the Firebase console. For example:
108+
109+
<img src="https://firebase.google.com/docs/app-check/app-check-metrics.png"
110+
alt="Screenshot of the App Check metrics page"
111+
class="screenshot"/>
112+
113+
The request metrics for each product are broken down into four categories:
114+
115+
- **Verified** requests are those that have a valid App Check token. After
116+
you enable App Check enforcement, only requests in this category will
117+
succeed.
118+
119+
- **Outdated client** requests are those that are missing an App Check
120+
token. These requests might be from an older version of the Firebase SDK
121+
before App Check was included in the app.
122+
123+
- **Unknown origin** requests are those that are missing an App Check token,
124+
and don't look like they come from the Firebase SDK. These might be from
125+
requests made with stolen API keys or forged requests made without the
126+
Firebase SDK.
127+
128+
- **Invalid** requests are those that have an invalid
129+
App Check token, which might be from an inauthentic client attempting to
130+
impersonate your app, or from emulated environments.
131+
132+
The distribution of these categories for your app should inform when you decide
133+
to enable enforcement. Here are some guidelines:
134+
135+
- If almost all of the recent requests are from verified clients, consider
136+
enabling enforcement to start protecting your backend resources.
137+
138+
- If a significant portion of the recent requests are from likely-outdated
139+
clients, to avoid disrupting users, consider waiting for more users to update
140+
your app before enabling enforcement. Enforcing App Check on a released
141+
app will break prior app versions that are not integrated with the
142+
App Check SDK.
143+
144+
- If your app hasn't launched yet, you should enable App Check enforcement
145+
immediately, since there aren't any outdated clients in use.
146+
147+
### Cloud Functions {#metrics-functions}
148+
149+
For Cloud Functions, you can get App Check metrics by examining your
150+
functions' logs. Every invocation of a callable function emits a structured log
151+
entry like the following example:
152+
153+
```json
154+
{
155+
"severity": "INFO", // INFO, WARNING, or ERROR
156+
"logging.googleapis.com/labels": {"firebase-log-type": "callable-request-verification"},
157+
"jsonPayload": {
158+
"message": "Callable header verifications passed.",
159+
"verifications": {
160+
// ...
161+
"app": "MISSING", // VALID, INVALID, or MISSING
162+
}
163+
}
164+
}
165+
```
166+
167+
You can analyze these metrics in the Google Cloud Console by [creating a
168+
logs-based counter metric](https://cloud.google.com/logging/docs/logs-based-metrics/counter-metrics)
169+
with the following metric filter:
170+
171+
```
172+
resource.type="cloud_function"
173+
resource.labels.function_name="YOUR_CLOUD_FUNCTION"
174+
resource.labels.region="us-central1"
175+
labels.firebase-log-type="callable-request-verification"
176+
```
177+
178+
[Label the metric](https://cloud.google.com/logging/docs/logs-based-metrics/labels#create-label)
179+
using the field `jsonPayload.verifications.appCheck`.
180+
181+
182+
## 5. Enable enforcement {#enable-enforcement}
183+
184+
To enable enforcement, follow the instructions for each product, below. Once you
185+
enable enforcement for a product, all unverified requests to that product will
186+
be rejected.
187+
188+
### Realtime Database, Cloud Firestore, and Cloud Storage {#enable-other}
189+
190+
To enable enforcement for Realtime Database, Cloud Firestore (iOS and Android), and Cloud Storage:
191+
192+
1. Open the [**Project Settings > App Check**](https://console.firebase.google.com/project/_/settings/appcheck)
193+
section of the Firebase console.
194+
195+
1. Expand the metrics view of the product for which you want to enable
196+
enforcement.
197+
198+
1. Click **Enforce** and confirm your choice.
199+
200+
Important: Cloud Firestore support is currently available only for Android and
201+
iOS clients. If your project has a web app, **don't enable Cloud Firestore
202+
enforcement** until web client support is available.
203+
204+
Note that it can take up to 10 minutes after you enable enforcement for it to
205+
take effect.
206+
207+
### Cloud Functions {#enable-functions}
208+
209+
See [Enable App Check enforcement for Cloud Functions](https://firebase.google.com/docs/app-check/cloud-functions).
210+
211+
212+
## Next steps
213+
214+
If, after you have registered your app for App Check, you want to run your
215+
app in an environment that App Check would normally not classify as valid,
216+
such as an emulator during development, or from a continuous integration (CI)
217+
environment, you can create a debug build of your app that uses the
218+
App Check debug provider instead of a real attestation provider.
219+
220+
See [Use App Check with the debug provider](debug-provider).

0 commit comments

Comments
 (0)