Error getting App Check token; using placeholder token instead - flutter

My app was working normally since today.I already included Firebase Storage in my Android Flutter App and it works after that today I get AppCheck Errors suddenly. I was not include App Check for our project or not enforced in settings. After that I was following the official documentation for initialization appcheck : https://firebase.flutter.dev/docs/app-check/usage.
This is my Kotlin MainActivity:
import android.os.Bundle
import com.google.firebase.FirebaseApp
import com.google.firebase.appcheck.FirebaseAppCheck
import com.google.firebase.appcheck.debug.DebugAppCheckProviderFactory
import io.flutter.embedding.android.FlutterActivity
class MainActivity : FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
FirebaseApp.initializeApp(/*context=*/ this);
val firebaseAppCheck = FirebaseAppCheck.getInstance()
firebaseAppCheck.installAppCheckProviderFactory(
DebugAppCheckProviderFactory.getInstance())
super.onCreate(savedInstanceState)
}
}
and this is my main():
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await FirebaseAppCheck.instance.activate();
runApp(MyApp());
}
I also added this to my app/build.gradle
dependencies {
implementation 'com.google.firebase:firebase-appcheck-debug:16.0.0-beta01'
}
When I make a request to firebase storage, I would expect something like this in my console:
D DebugAppCheckProvider: Enter this debug secret into the allow list in the Firebase Console for your project: 123a4567-b89c-12d3-e456-789012345678
Instead, I'm getting an error:
2021-11-21 18:11:51.442 2091-3452/com.sekspir.grind4gain W/ExponenentialBackoff: network unavailable, sleeping.
2021-11-21 18:11:53.500 2091-3452/com.sekspir.grind4gain W/StorageUtil: Error getting App Check token; using placeholder token instead. Error: com.google.firebase.FirebaseException: Error returned from API. code: 403 body: App attestation failed.
2021-11-21 18:12:11.136 2091-3633/com.sekspir.grind4gain V/NativeCrypto: SSL handshake aborted: ssl=0xdaa42da8: I/O error during system call, Connection reset by peer
Did I miss something here? I am using a real Android device with flutter debug build.
This is Firestore AppCheck Stats looks both of request income
But in Storage session there are not any request fail or success.

Can you double check that you correctly enabled the enforcement ?
It is required to work with Firebase Storage solutions.
Are you using your app in "PWA" mode or in "Native" mode ?
The Recaptcha may be mandatory depending on how your app is distributed.
await FirebaseAppCheck.instance.activate(
webRecaptchaSiteKey: 'recaptcha-v3-site-key',
);
I'm not sure about your implementation of the appcheck-debug dependency on the Android Native side.
Since it's already implemented by the Flutter library itself, you should remove it.
Personal note : I had troubles with FirebaseAppCheck on some devices, while it was working perfectly on other devices.
This library is still in beta and I would recommend to wait before using it in production.

Related

firebase/flutter - App Check debug provider in an emulator

I try to get a local debug token according to the instructions, but I don't see any in the console. I implemented this code as given. Is it maybe because the release and debug app-check don't work at the same time?
Guide: https://firebase.google.com/docs/app-check/android/debug-provider?hl=en#java_1, Point 3 doesn't work for me
MainActivity.java
import com.google.firebase.FirebaseApp;
import com.google.firebase.appcheck.FirebaseAppCheck;
import com.google.firebase.appcheck.playintegrity.PlayIntegrityAppCheckProviderFactory;
import com.google.firebase.appcheck.debug.DebugAppCheckProviderFactory;
FirebaseApp.initializeApp(/*context=*/ this);
FirebaseAppCheck firebaseAppCheck = FirebaseAppCheck.getInstance();
firebaseAppCheck.installAppCheckProviderFactory(PlayIntegrityAppCheckProviderFactory.getInstance());
firebaseAppCheck.installAppCheckProviderFactory(DebugAppCheckProviderFactory.getInstance());
build.gradle
implementation 'com.google.firebase:firebase-appcheck-debug:16.1.1'
is there maybe another way to get the local debug token so i can add it in the firebase console?

Hosting a web server in a local enviroment using only Flutter

Is it possible to host a Flutter web app on a local environment using a Flutter desktop-based app?
The google-search for a solution like this can be difficult, since it involves many keywords that lead to similar situations (online hosting when you need a local solution, command-line only solution, and so on).
After some digging, I ended up using the shelf package to deploy my own Flutter web app on a local network. I developed this for Windows only, so I can't guarantee it will work on other platforms.
First thing to do is obviously adding the shelf package in your pubspec.yaml: after that, this is how my main method looks like
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf_router/shelf_router.dart' as shelf_router;
[...]
void main() async{
[...]
var secureContext = SecurityContext();
try {
//privKey and cert are the String names of the two files for the SSL connection,
//placed in the root directory of the flutter project or along with the .exe file (when released)
secureContext.usePrivateKey(privKey);
secureContext.useCertificateChain(cert);
} catch (error) {
logger.e("Error on init SecurityContext");
}
try {
//this is the handler that deploys the files contained in 'webAppFolder': I just simply pasted the result of
//the flutter webapp building inside (the index.html file is the default one for flutter web)
//and put the folder in the root of the flutter project (or, again, in the same folder with the .exe file when released)
final _staticHandler = createStaticHandler("webAppFolder", defaultDocument: 'index.html');
//this I kept just for a reminder on how to deploy a static page, if needed
final _router = shelf_router.Router()
..get(
'/time',
(request) => shelf.Response.ok(DateTime.now().toUtc().toIso8601String()),
);
final cascade = shelf.Cascade()
.add(_staticHandler)
.add(_router);
try {
var server = await shelf_io.serve(
cascade.handler,
InternetAddress.anyIPv4,
mainPort, //this is the number of the port on which the webapp is deployed (I load this from a .ini file beforehand
securityContext: secureContext,
);
// Enable content compression
server.autoCompress = true;
logger.i("Serving at https://${server.address.host}:${server.port}");
} catch (err) {
logger.e("Error while serving");
logger.e(err.toString());
}
} catch (err) {
logger.e("Error while creating handler");
logger.e(err.toString());
}
runApp(MaterialApp(
[...]
This is the part related to the deploy of a web app: since the flutter desktop app already provides a GUI, I used that to add some maintenance and testing utilities to check if everything is working fine.
For more details regarding shelf, refer to their API on their pub.dev page.

Flutter WebSocket works in web application but not in android emulator

'final channel = WebSocketChannel.connect(
Uri.parse('wss://echo.websocket.org'),
);'
can create and connect in web application
but can't connect in android emulator
There are two libraries implementing WebSocket class - one that works on web, the other on Andoroid.
You can sort this out by creating a simple factory function. You will need to create several files:
websocket_client_factory.dart
export 'websocket_client_factory_null.dart'
if (dart.library.html) 'websocket_client_factory_web.dart'
if (dart.library.io) 'websocket_client_factory_server.dart';
websocket_client_factory_null.dart
import 'package:web_socket_channel/web_socket_channel.dart';
WebSocketChannel makeWsClient(String url) {
throw 'Platform not supported';
}
websocket_client_factory_server.dart
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
WebSocketChannel makeWsClient(String url) =>
IOWebSocketChannel.connect(url, protocols: ['graphql-ws']);
websocket_client_factory_web.dart
import 'package:web_socket_channel/html.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
WebSocketChannel makeWsClient(String url) =>
HtmlWebSocketChannel.connect(url, protocols: ['graphql-ws']);
Now, from your original file just import the factory file, and call the factory function:
import 'package:./websocket_client_factory.dart';
...
var channel = makeWsClient(wssUrl);
In my project WebSocket connection needs authentication
In web application automatically pass cookies and authentication token in
websocket connection
But in Mobile Application we need to set cookies and authentication
token manually
When I done this resolved my issue

How to seed the Firebase Storage Emulator?

I'm trying to seed the Firebase Storage Emulator. I've added a json file to my project and I'm trying to upload this file to the Storage Emulator during the seed phase:
await firebaseAdmin
.storage()
.bucket()
.upload(path.join('./data/cars.json'), {
destination: `vehicles/cars.json`,
});
Unfortunately this does not seem to work and I'm running into the following error:
TypeError: Cannot read property 'length' of undefined
The way I did this was by using firebase-tools
firebaseCli.emulators.start({
project: "project-id",
import: "path-to-file.json"
})
This will work only if the firebase emulator setup is done correctly and the data you are trying to import has the correct format.
For the Firebase Storage Emulator to work you need to initialize it in the Admin SDK:
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert('path/to/credential'),
storageBucket: "bucket-name",
});

PWA not working correctly offline. Uncaught (in promise) TypeError: Failed to fetch

I am trying to convert a simple webpage I have into a PWA in case the site it uses goes down.
I think I have done the majority of the work. The page is installable on my phone and passes all the Chrome lighthouse tests. But I get the following warning,
Web app manifest meets the installability requirements
Warnings: Page does not work offline. The page will not be regarded as installable after Chrome 93, stable release August 2021.
I also get the following warning and error in console,
The FetchEvent for "https://dannyj1984.github.io/index.html" resulted in a network error response: the promise was rejected.
Promise.then (async)
(anonymous) # serviceWorker.js:30
serviceWorker.js:1 Uncaught (in promise) TypeError: Failed to fetch
There is then a warning saying the site cannot be installed as does not work offline. I have read the chrome dev article which says from the chrome release in Aug21 apps that dont work offline wont be installable. But I am stuck on which part of my fetch is causing an issue. The code in my service worker is,
const TGAbxApp = "TG-ABX-App-v1"
const assets = [
//paths to files to add
]
self.addEventListener("install", installEvent => {
installEvent.waitUntil(
caches.open(TGAbxApp).then(cache => {
cache.addAll(assets)
})
)
})
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
The above code for the fetch part of the service worker I took from Google and as I understand it, it first checks if there is data in the cache stored on install, if not it will request it from the network.
https://developer.chrome.com/blog/improved-pwa-offline-detection/
From Chrome 89 March 2021, it gives a warning if this check does not pass:
The installed service worker fetch event returns an HTTP 200 status code (indicating a successful fetch) in simulated offline mode.
So, in your case, the service worker should return a cached 'index.html' when fetch(event.request) is failed.
I've had the same problem. I re enabled the cache through the developer console->network. fixed