I am trying to get Firebase App Check working in a Vue 3 web app. I have Firebase configured and reCAPTCHA v3 configured.
Here is the code where I initialize Firebase and App Check. I am logging the recaptcha site key to console to make sure the env variables are getting injected correctly.
const fbConfig = {
apiKey: import.meta.env.VITE_APP_FIREBASE_APIKEY,
authDomain: import.meta.env.VITE_APP_FIREBASE_AUTHDOMAIN,
projectId: import.meta.env.VITE_APP_FIREBASE_PROJECTID,
appId: import.meta.env.VITE_APP_FIREBASE_APPID,
storageBucket: import.meta.env.VITE_APP_STORAGEBUCKET,
messagingSenderId: import.meta.env.VITE_APP_MESSAGINGSENDERID,
}
const fbapp = initializeApp(fbConfig)
if (location.hostname === "localhost") {
self.FIREBASE_APPCHECK_DEBUG_TOKEN = true;
}
console.log("APPCHECK Token: ", import.meta.env.VITE_APP_RECAPTCHA_SITEKEY)
const appCheck = initializeAppCheck(fbapp, {
provider: new ReCaptchaV3Provider(import.meta.env.VITE_APP_RECAPTCHA_SITEKEY),
// Optional argument. If true, the SDK automatically refreshes App Check
// tokens as needed.
isTokenAutoRefreshEnabled: true
});
This works as expected on local host where the debug token is used. When I deploy to a live site I get this error.
{ code: 400, message: "Invalid app resource name: \"projects/<name removed>/apps/\"<code removed>\"\".", status: "INVALID_ARGUMENT" }
Any thoughts?
Found the problem. The appId was getting quoted in the environment variables for some reason. Fixing that fixed the issue.
Related
I am trying to enable firebase analytics in my existing firebase project. The project is a static React website that only uses Firebase hosting.
Following this get start tutorial, I am getting the following error in my console:
Ignored "config" command. Invalid arguments found
Searching how to solve this problem, I found this comment and checked that my webConfig get request is not returning the measurementId. However I couldn't find any info about how to correct it.
//firebase.js
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics} from "firebase/analytics";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "{ApiKey}",
authDomain: "{projectId}.firebaseapp.com",
projectId: "{projectId}",
storageBucket: "{projectId}.appspot.com",
messagingSenderId: "{messagingSenderId}",
appId: "{appId}",
measurementId: "{measurementId}",
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const analytics = getAnalytics(app);
WebConfig call (Http 200, Get):
response:
{
"projectId": "{projectId}",
"appId": "{appId}",
"storageBucket": "{projectId}.appspot.com",
"authDomain": "{projectId}.firebaseapp.com",
"messagingSenderId": "{messagingSenderId}"
}
Is there any config that I am missing? what should I do to make it work?
There could be something wrong with the stream for your web app that’s why the measurementId is not being configured. You could try to unlink and relink to your Google Analytics integration which usually resolves any broken integration. Make sure that the currently linked GA property is the one you’re going to use for relinking to avoid losing your data.
importScripts("https://www.gstatic.com/firebasejs/9.8.3/firebase-app-compat.js");
importScripts("https://www.gstatic.com/firebasejs/9.8.3/firebase-messaging-compat.js");
// Initialize the Firebase app in the service worker by passing the generated config
const firebaseConfig = {
apiKey: "AIzaSyDk4dYeydr4q3npWx4iqKWejq33r1E",
authDomain: "tengage-33e12.fireeapp.com",
projectId: "tengage-33e12",
storageBucket: "tengage-33e12.appspot.com",
messagingSenderId: "1076165210",
appId: "1:1076165210:web:c9560924940a068ce3",
measurementId: "G-5FMCR8M0G8",
};
firebase.initializeApp(firebaseConfig);
// Retrieve firebase messaging
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
console.log(" message ", payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
I have one React js project in which I have to integrate the FCM.
I have added firebase-messaging-sw.js in public folder.
and added the firebbase dependency also.
when I am trying to get token i am getting the error.
SecurityError: Failed to register a ServiceWorker for scope ('http://localhost:3005/') with script ('http://localhost:3005/firebase-messaging-sw.js'): The script has an unsupported MIME type ('text/html').
But with the same firebase credentials when I tried to get the token in the newly created application its giving the token.
The error that is mentioned may occur due to a few reasons , one of which could be an error in the design pattern or syntax. However, it means that any requests for unknown text files initially get redirected to index.html, and therefore return with the MIME type of "text/html", even if it's actually a JavaScript or SVG or some other kind of plaintext file.
Refer below for example:
// Load React App
// Serve HTML file for production
if (env.name === "production") {
app.get("*", function response(req, res) {
res.sendFile(path.join(__dirname, "public""index.html"));
});
}
You may try to add a specific route for service-worker.js before the wildcard route:
app.get("/service-worker.js", (req, res) => {
res.sendFile(path.resolve(__dirname, "public", "service-worker.js"));
});
app.get("*", function response(req, res) {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
Now, when the browser looks for service-worker.js, it will return it with the correct MIME type.
(Note that if you try adding the service-worker.js route after the wildcard, it won't work because the wildcard route will override.)
You also may want to check if the URL http://localhost:3005/firebase-messaging-sw.js, is getting served and its MIME type from the browser interface.
Also , please make sure that the service worker file is generated (Chrome DevTools -> Sources -> Filesystem). You may receive such an error if the above example service-worker.js file is not generated at all (check your deployment script).
You may also refer the links below for more insight:
[1] : https://firebase.google.com/docs/cloud-messaging/js/client#access_the_registration_token
[2] : https://firebase.google.com/docs/cloud-messaging/server
[3] : FCM getToken() Failed to register a ServiceWorker for scope error Flutter web
I have have an GCP Identity Platform + Firebase app using a Microsoft Active Directory Oauth Provider.
When calling signInWithRedirect it gets a 400 with the url
https://www.googleapis.com/identitytoolkit/v3/relyingparty/createAuthUri?key=<api-key>
(note, I am redacting my specific values)
The payload it sends looks like
{
"providerId": "microsoft.com",
"continueUri": "https://<my-gcp-project-id>.firebaseapp.com/__/auth/handler",
"customParameter": { "tenant": "<my-domain>", "redirect_uri": "http://localhost:3000/callback" }
}
Config
const config = {
apiKey: "<api-key>",
authDomain: "<my-domain>",
};
const firebaseApp = firebase.initializeApp(config);
const firebaseAuthApp = firebaseAuth.getAuth(firebaseApp)
const provider = new firebaseAuth.OAuthProvider('microsoft.com');
provider.setCustomParameters({
tenant: 'mydomain.com',
redirect_uri: 'http://localhost:3000/callback',
});
Triggering auth:
const handleClick = () => {
firebaseAuth.signInWithRedirect(firebaseAuthApp, provider)
}
The issue was an incorrect redirect URI defined in the Azure console Active Directory application configuration.
To get my app working (locally) I provided the firebase auth handler callback:
Reference:
https://learn.microsoft.com/en-us/troubleshoot/azure/active-directory/error-code-aadsts50011-reply-url-mismatch
I have integrated notifications for flutter web, its working fine when i give permission for the first time, but lets say user has denied it so is there any way to request notifications permission again to get token in dart files from javascript files ?
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-messaging.js');
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: 'favicon.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
You can follow a similar permission call posted as an Answer in this post. For your use case, you'll need to use push permission since Firebase Cloud Messaging for web needs Push API support as mentioned in the official docs
Use dart:html package for the permission requests using Web API. Import the dart:html package, and set a prefix. In this sample, we used 'html'
import 'dart:html' as html;
Create a helper method to check for push permissions.
checkPushPermission() async {
var pushPermission = await html.window.navigator.permissions.query({"name": "push"});
print('push permission: ${pushPermission.state}')
}
Call checkPushPermission() to verify the current push permission state, and it should display the relevant permission dialog.
checkPushPermission();
Be reminded that FlutterFire Cloud Messaging is yet to be fully supported for Web, and there could be quirks in its current state. Also, be aware of Web API's browser compatibility.
I did not test it myself but it seems you should call the browser "requestPermission" API:
https://developer.mozilla.org/en-US/docs/Web/API/Notification/requestPermission
https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API
For Flutter I have seen there is this call in "dart:html" package:
https://api.flutter.dev/flutter/dart-html/Notification/requestPermission.html
Migrating to firebase 3.0 but it's failed to initialize.
var firebase = require('firebase');
// Initialize Firebase
var config = {
apiKey: "key",
authDomain: ".firebaseapp.com",
databaseURL: ".firebaseio.com",
storageBucket: ".appspot.com",
};
firebase.initializeApp(config);
module.exports ={
return : {
auth : firebase.auth,
database : firebase.database(),
storage : firebase.storage()
}
}
node_modules\firebase\auth-node\auth.js:61
throw new Error('Invalid service account provided');
at \node_modules\firebase\auth-node\index.js:31:9
at \node_modules\firebase\app-node.js:11:272
installed firebase : 3.0.2,
node : 4.4.2
"express": "^4.13.4"
Try to copy the correct setup settings from the Web Setup tab with the relevant APIkeys.
Try to delete the [DEFAULT] app and reinitialize. I think the code is somthing like
firebase.app.delete().then(function(){
)};
I faced the same issue. Check it here: Firebase "throw new Error('Invalid service account provided');" error message.
You need to create a service account and add it to your firebase app configuration.
firebase.initializeApp({
serviceAccount: "path/to/serviceAccountCredentials.json",
databaseURL: "https://databaseName.firebaseio.com"
})