Nodejs: firebase.auth().signInWithCustomToken(token) generate "Object has no method 'signInWithCustomToken'" error - firebase

With new firebase version, y need to access by node.js at my firebase application.
var firebase = require("firebase");
var parms={.......}
firebase.initializeApp(parms);
var token = firebase.auth().createCustomToken('123'); //Token generated successfully
//Line below throws error
firebase.auth().signInWithCustomToken(token).catch(function(error) {
//do something
});
If I use signInWithCustomToken from javascript in the browser, it works fine. But if I use it from command line: node file.js, it throws the error: firebase.auth().signInWithCustomToken(token) generate "Object has no method 'signInWithCustomToken'" error
Why?

On this part the web and node apis are different.
As stated in the Upgrade Guide (https://firebase.google.com/support/guides/firebase-web#update_your_authentication_code_numbered)
you need to use a service account for node.js apps. A good point to start is this page: https://firebase.google.com/docs/database/server/start#section-account
I would have loved to paste you the links to the auth api pages, but I'm only allowed to post 2 links. :)

Related

Why Isn't app.initailzation() working in my Teams Add-in OAuth flow?

I am trying to get simple auth in my Teams app working with Adobe ID (a third party Oauth provider that I use on my site).
I am following the sample here. Everything is working to authorize with the Adobe ID, but when it gets to my end authentication page like this, I get an exception thrown with the message "SDK initialization timed out." when I call await app.initialize();. The sample shown does not have the await term before app.initialize(). Is that incorrect? If I remove the await, my code later on to notify authentication of success, fails with the exception "The library has not yet been initialized".
authentication.notifySuccess("Yippee");
What do I need to do to allow app.initialize() to work?
How can the sample work if there is no await before it?
Here is the TypeScript code for my OAuth End page that is loaded after the Adobe Authentication succeeds.
import $ from "jquery";
import {app, authentication} from "#microsoft/teams-js";
startup();
async function startup(){
try{
$("#status").text("Initializing");
await app.initialize();
$("#status").text("Initialized");
console.log("notifying of success");
authentication.notifySuccess("Yippee");
}
catch(error){
handleError(error, "initializing");
}
}
function handleError(error:Error, context: string){
console.error(`💥 Error ${context}: ${error.message}`);
$("#status").text(error.message);
}
What version of the js library are you using?
There have been some changes to how app.initialize is handled depending on the version of the SDK you are using- see details here
https://learn.microsoft.com/en-us/microsoftteams/platform/tabs/how-to/using-teams-client-library?tabs=typescript%2Cmanifest-teams-toolkit#callbacks-converted-to-promises
You should be able to see this in package.json for typescript, although I think there may be other areas where you may need to update this.
Try this with the version referenced in the sample- 2.0.0 does that resolve the issue?
re: await- that just tells the application to wait until a response is returned (a success or failure) before moving on to the next line. In your case, you need the await as your next line is dependent on the value of status, but your function is async, so it won't block the execution of other async functions. You want to use await where you have other requests that must have a response on that call- like getauthtoken.

Missing initial state in WebAuthenticator login attempt

working on a .NET MAUI app and am trying to implement Firebase Authentication with the help of WebAuthenticator in MAUI. I get to the login form in a browser, but after logging in get the error
Unable to process request due to missing initial state. This may happen if browser sessionStorage is inaccessible or accidentally cleared.
This is the code that calls the authenticator
await client.SignInWithRedirectAsync(FirebaseProviderType.Google, async uri =>
{
var options = new WebAuthenticatorOptions
{
Url = new Uri(uri),
CallbackUrl = new Uri("com.companyname.myappname://callback/"),
PrefersEphemeralWebBrowserSession= true
};
var res = await WebAuthenticator.Default.AuthenticateAsync(options);
});
I think the problem could be the callback URL, but I'm not sure how to write it differently since I'm not using a backend API. Does anyone have any suggestions?
Thanks!
P.S. This happens with bost Firebase Google auth and Facebook login
You can try to clear the chrome browser data and reload the page to see if it works. This is a known problem of firebase. You can continue to follow up this github iissue: Unableto process request due to missing initial state.

Custom logging from firebase function

I'm trying to follow this guide to put some custom logging into a firebase function. The function itself is running, and I can see the data being passed in (it's an https 'callable' function). But as soon as it hits the line where it tries to actually write that log entry, I get "Error: 7 PERMISSION_DENIED"
Since the console.log() calls write to the cloud logs, I'd assumed the firebase function has access to Cloud Logging. But perhaps it needs additional permission? I can't find any reference to where this should be set on that page though.
// Logging, logName, region, functions are provided by the surrounding app
const logging = new Logging()
const log = logging.log(logName)
const METADATA = {
resource: {
type: 'cloud_function',
labels: {
function_name: 'CustomLog',
region
}
}
};
exports = module.exports = functions.https.onCall(async data => {
const exVersion = 6
const exId = data.exId
console.log('***** exVersion:', exVersion, 'exId:', exId) // exId from caller
const entry = log.entry(METADATA, data.error) // data.error from caller
console.log('METADATA:', METADATA) // Shows in Logs Explorer
console.log('entry:', entry) // Shows in Logs Explorer
log.write(entry) // Results in Error: 7 PERMISSION_DENIED
return {
exVersion,
exId,
}
})
If I run it from the CLI using firebase function:shell, the log entry is created correctly, so I'm pretty confident the code is correct.
OK, I finally tracked it down. According to this answer, the service account used by firebase functions is {project-id}#appspot.gserviceaccount.com, and in my project, that account did not have the 'Logs Writer' role. Adding that role solves the problem.
I find it odd that the firebase functions don't need that role to log messages using console.log(), but perhaps that call is intercepted by the functions environment, and the logs are written as a different service account. It also explains why the functions running locally were able to write the logs, as they run using the 'owner' service account, which has full access.
According to the Firebase documentation page you have linked:
The recommended solution for logging from a function is to use the
logger SDK. You can instead use standard JavaScript logging calls such
as console.log and console.error, but you first need to require a
special module to patch the standard methods to work correctly:
require("firebase-functions/lib/logger/compat");
Once you have required the logger compatibility module, you can use console.log() methods as normal in your code.
Thus you might to require this library, however I am not sure this is producing your "Error: 7 PERMISSION_DENIED error, but you might also try some solutions that have worked for some members of the community.
Perhaps the logging API is not enabled in your project. You'll get a permission denied error when attempting to use it in that case.
It's a couple levels in, but the guide you linked points to
https://github.com/googleapis/nodejs-logging#before-you-begin, which includes a step to "Enable the Cloud Logging API"

Firebase and LinkedIn Auth integration unknown route

I've been examining this code base as an example of how to implement LinkedIn authorization to my project with a Firebase Backend. One thing I'm confused about is these lines:
var code = getURLParameter("code");
var state = getURLParameter("state");
var error = getURLParameter("error");
if (error) {
document.body.innerText = "Error back from the LinkedIn auth page: " + error;
} else if (!code) {
// Start the auth flow.
window.location.href = "/redirect";
}
at window.location.href = '/redirect', I believe it is meant to invoke the cloud function called "redirect". In my code base, it simply goes to an unknown route and triggers my fallback. Am I wrong about the purpose of this line of code? Does anyone know any possible reasons it's not triggering the cloud function (console says 0 invocations)? What other information should I look into to try to debug this?
To provide a bit fuller of an answer:
The example you provided relies on a Firebase.json file. This file provides configuration if (and only if) your application is hosted with Firebase hosting (see docs).
If you expect to host your app elsewhere, you'll need to make sure your /redirect path points to the Firebase function URL itself (probably something like https://us-central1-project-name.cloudfunctions.net/redirect). In the authorization flow, the LinkedIn module in the example repo then will redirect to either a default or a configured callback url.

Evernote Windows SDK Csharp SampleAppAdvanced - can't authenticate

I am trying to run the Csharp sampleAppAdvanced from this code https://github.com/evernote/evernote-cloud-sdk-windows
I substituted the consumer key and secret with those that I got in the email when I requested the API key.
ENSessionAdvanced.SetSharedSessionConsumerKey("xyz","123","sandbox.evernote.com");
if (ENSession.SharedSession.IsAuthenticated == false)
{
ENSession.SharedSession.AuthenticateToEvernote();
}
But I always end up hitting an error at this point
ENNoteRef myRef = ENSession.SharedSession.UploadNote(myNoteAdv, null);
With exception reading "Exception of type 'EvernoteSDK.ENAuthExpiredException' was thrown."
On the console the error reads "EvernoteSDK: ENSession is unauthenticating."
Am I missing something? I know the Application is authorized for access.
The other sample code called sampleApp, doesn't throw an error but doesn't display notes either.
When you register the api, did you choose Basic Access or Full Access?

Resources