Firestore: code 16 (Request had invalid authentication credentials) - javascript

i am trying to access Firestore with admin permissions via private key and admin permissions so i can use it for queries and stuff in the backend.
//i import fb-admin
const firebaseAdmin = require('firebase-admin')
//i initialize as admin with a valid credential
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert('./pathto/myprivatekeyinfo.json')
})
//i initialize firestore
var dba = firebaseAdmin.firestore()
//i test the connection by listing all the available collections
dba.getCollections().then(collectionList => {
collectionList.forEach(collection => {
console.log(collection.id) //print available collections
}
},error => console.error(JSON.stringify(error,null," "))) //print error
It seems exactly like instructed in the documentation, but my problem is that with some computers that i try to execute Node in, i only manage to connect at random on a few.
Sometimes i connect and it goes fine, printing the available collections as it should, but most of the time all i get is this error for invalid credentials
{
"code": 16,
"metadata": {
"_internal_repr": {
"www-authenticate": [
"Bearer realm=\"https://accounts.google.com/\""
]
}
},
"details": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"note": "Exception occurred in retry method that was not classified as transient"
}
i've tried changing nothing and it works sometimes on some computers where i test the exact same code, but in others it doesn't, and trying to get a new private key via the firebase console changes nothing in the matter. When i try to connect it sometimes takes too long just to get this error or it does not call back at all. The link provided isn't helpful either, as it only gives some JS code for regular access via the front end to login with google which isn't my use case at all in this situation (i've tried the "configure a project" button too).
is there anything that i am doing really wrong here? why does it work sometimes although changing nothing and sometimes it just doesn't?
i appreciate any help

This error is basically the same to this one (Not able to send device push notification due to app/invalid-credential error), where the clock of the computer needs to be synced to the clock of the firebase server.
i was stuck trying to test it in various computers (all with the wrong set up clock) without being able to connect before a friend tried to point out that, so i tested and it worked.
The solution that worked for me was definitely to check the set up clock on the computer.

Related

How to get Azure AD access token in Static Web App?

I have a vanilla Vue.JS SWA that uses a standard Azure AD authentication via these settings in staticwebapp.config.json:
"auth": {
"identityProviders": {
"azureActiveDirectory": {
"registration": {
"openIdIssuer": "https://login.microsoftonline.com/common/v2.0",
"clientIdSettingName": "AZURE_CLIENT_ID",
"clientSecretSettingName": "AZURE_CLIENT_SECRET"
}
}
}
}
An app with AZURE_CLIENT_ID is registered in Azure AD. Authentication is called via standard
/.auth/login/aad
endpoint. I can successfully log in and log out. "/.auth/me" endpoint returns clientPrincipal object with all user details (roles, id, etc) and claims.
Now I want to call MS graph API https://graph.microsoft.com/v1.0/me, but don't know how to get the access token to set the Authorization header in the request. I can see that there is a AppServiceAuthSession cookie is set, however it is not a token.
I have seen this https://stackoverflow.com/questions/59860238/how-to-convert-azure-cookie-appserviceauthsession-to-a-valid-oauth-jwt-access-to , however reconstructing the whole auth flow looks unnecessary as I am logged in already.
Will appreciate any advice. Many thanks!
Tried to all MS Graph API as is, but as expected, got "message": "Access token is empty."
Also had a look at azure/msal-browser module in a hope to get the token silently, but it looks super complex and badly documented for a JS novice like me.
The following microsoft document shows getting the access on behalf of the user, you can refer this DOC to get the access token.
Hope this helps.

How do I debug authentication in Firebase?

Currently, when I set authentication signinflow to redirect, the login process doesn't complete, although it does go to the Google or Facebook login screen. However, when I set the signinflow to popup, the authentication process works as intended. What I'm curious about is how do I go about debugging the authentication in Firebase? The console only shows front-end javascript related code obviously, and the DebugView in the firebase console doesn't show anything when I login or logout whether it's via popup or redirect. What are the steps involved in finding out where the authentication error is in relation to the redirect signinflow mode?
My app.js code is as follows:
firebaseUI.start('#firebaseui-auth-container', {
signInFlow: 'redirect',
signInSuccessUrl: 'http://www.bing.com',
signInOptions: [
firebaseDB.firebase_.auth.EmailAuthProvider.PROVIDER_ID,
firebaseDB.firebase_.auth.GoogleAuthProvider.PROVIDER_ID,
firebaseDB.firebase_.auth.FacebookAuthProvider.PROVIDER_ID
],
});
firebase.auth().onAuthStateChanged(user => {
if (user) {
console.log(user.displayName);
} else {
console.log('no user signed in');
}
});
Several tips come to mind:
(1) Look carefully at the JavaScript console logs on your browser. JavaScript is rather notorious for "spit out an error-message (in a place where you'd ordinarily never see it ...) and keep going."
(2) Look carefully at the server-side logs, both for Firebase and for the web server. The sequence of interest probably involves one or more "round trips" between several different pieces of software, and you need to methodically, systematically reconstruct exactly what took place and in what sequence. "The whole time-line."
(3) "Don't assume!" "Trust, but verify," as they say. Don't act on any "assumption" as to what the actual problem is – e.g. here you probably "assume" that it's a problem in "Firebase authentication." Assumptions can send you "chasing after white rabbits" for a distressingly long time, only to come up empty-handed. (Trust me on this one ...)
You probably won't get too much useful information from a "TCP/IP dumper" (such as tcpdump ...) because the communications is probably encrypted.

Adding a document in Firestore from web app is not working and not returning an error

Suddenly my code for adding new documents to Firestore is not working and not returning an error. I thought perhaps it was a network issue but Authentication and creating new users is working fine. My network connection is also quite solid.
[EDIT] I've switched on debug mode and a call to Firestore is made with a documentChange request and the correct data fields. The document is never created though. I am on the latest Firestore release.
I tried this simplified add to my collection:
firebase.firestore().collection('biff').add({
boff: 0,
baff: 5
}).catch(function(error) {
console.error('There was an error uploading a file to Cloud Storage:', error);
});
Here are my security rules: (I also tried completely public writing)
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth.uid != null;
}
}
}
There are no error messages generated and the new document never appears in my collection. I can authenticate and create new users. Is it possible that authentication is live but somehow my firebase SDK thinks that there is no connection to firestore so its queueing up the documnent writes?
[UPDATE] I noticed that an earlier alpha version of my frontend was still able to write new documents. When I listed the projects firebase knew about in the CLI it listed an older firebase project. So I did 'firebase use --add' and chose my new firebase project and then did a 'firebase init' to reset everything except my index.html. I then did a 'firebase deploy' and lo and behold my deployed version is able to write new documents. My localhost version still is not able to write them though. So very odd. So I am half way there with a solution. All ideas welcome on whats happening on my local machine to stop writes still ...
Once I used a button instead of a form submit to trigger the routine with the document.add then it all worked from localhost, server and mobile. In the broken version the form would continue processing and leave the user in the main view in a state where that url and all urls afterwards had a parameter (?topic=Business) appended to them. From then on the document.add would no longer work. By moving to a button and using e.preventDefault it now works every time and all the urls remain clear. (no idea why this side effect wedged firestore add)
var postOfferElement = document.getElementById('postoffer');
postOfferElement.addEventListener('click', function(e) {
e.preventDefault();
saveOffer();
});
In saveOffer:
firebase.firestore().collection('offers').add({
created: firebase.firestore.FieldValue.serverTimestamp(),
owner: getUserID(),
name: getUserName(),
pic: getProfilePicUrl(),
completes: 0,
favs: 0,
offer: offerText,
topic: topicText,
exp: expText
});

How can I Choose Specifc Users to Log Into my Javascript SPA in Azure AD?

I'm using a Javascript SPA to return a query from Microsoft Graph through the Azure AD application, and it works just fine!
The problem is when I try to loggout from the application, it says I was successfully logged out but if try to log in with another user, it logs into the previous one, in this case, me, without even asking for password.
I needed that this application could log in just few people in my organization, but anyone with "#example.com" can access my application, without the need to be signed to it or not.
I've already cleared the browser's cache and cookies and it doesn't work. Already configured the app to store the cache in the session but it also failed.
The code I'm using is available in:
https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-javascript-spa
The only differences are that I'm using another querys instead the "https://graph.microsoft.com/v1.0/me" and the permissions needed to get them.
I just needed a way to choose specific people to log into the application instead of all the organization and to fix this logout problem.
If I understood you well, I believe your solution is the option select_account.
Here is a code snippet to illustrate:
const clientApplication = new Msal.UserAgentApplication(config);
const loginRequest = {
scopes: [config.webApiScope],
prompt: "select_account",
}
clientApplication.loginPopup(loginRequest).then(function (loginResponse) {
//your code
});

facebook graph api node.js invalid appsecret_proof

this is my first post so please go easy on me!
I am a beginning developer working with javascript and node.js. I am trying to make a basic request from a node js file to facebook's graph API. I have signed up for their developer service using my facebook account, and I have installed the node package for FB found here (https://www.npmjs.com/package/fb). It looks official enough.
Everything seems to be working, except I am getting a response to my GET request with a message saying my appsecret_proof is invalid.
Here is the code I am using (be advised the sensitive info is just keyboard mashing).
let https = require("https");
var FB = require('fb');
FB.options({
version: 'v2.11',
appId: 484592542348233,
appSecret: '389fa3ha3fukzf83a3r8a3f3aa3a3'
});
FB.setAccessToken('f8af89a3f98a3f89a3f87af8afnafmdasfasedfaskjefzev8zv9z390fz39fznabacbkcbalanaa3fla398fa3lfa3flka3flina3fk3anflka3fnalifn3laifnka3fnaelfafi3eifafnaifla3nfia3nfa3ifla');
console.log(FB.options());
FB.api('/me',
'GET',
{
"fields": "id,name"
},
function (res) {
if(!res || res.error) {
console.log(!res ? 'error occurred' : res.error);
return;
}
console.log(res);
console.log(res.id);
console.log(res.name);
}
);
The error I am getting reads:
{ message: 'Invalid appsecret_proof provided in the API argument',
type: 'GraphMethodException',
code: 100,
fbtrace_id: 'H3pDC0OPZdK' }
I have reset my appSecret and accessToken on the developer page and tried them immediately after resetting them. I get the same error, so I don't think that stale credentials are the issue. My
console.log(FB.options())
returns an appropriate looking object that also contains a long hash for appSecretProof as expected. I have also tried this code with a number of version numbers in the options (v2.4, v2.5, v2.11, and without any version key). Facebook's documentation on this strikes me as somewhat unclear. I think I should be using v2.5 of the SDK (which the node package is meant to mimic) and making requests to v2.11 of the graph API, but ??? In any case, that wouldn't seem to explain the issue I'm having. I get a perfectly good response that says my appSecretProof is invalid when I don't specify any version number at all.
The node package for fb should be generating this appSecretProof for me, and it looks like it is doing that. My other info and syntax all seem correct according to the package documentation. What am I missing here? Thank you all so much in advance.
looks like you have required the appsecret_proof for 2 factor authorization in the advance setting in your app.
Access tokens are portable. It's possible to take an access token generated on a client by Facebook's SDK, send it to a server and then make calls from that server on behalf of the client. An access token can also be stolen by malicious software on a person's computer or a man in the middle attack. Then that access token can be used from an entirely different system that's not the client and not your server, generating spam or stealing data.
You can prevent this by adding the appsecret_proof parameter to every API call from a server and enabling the setting to require proof on all calls. This prevents bad guys from making API calls with your access tokens from their servers. If you're using the official PHP SDK, the appsecret_proof parameter is automatically added.
Please refer the below url to generate the valid appsecret_proof,and add it to each api call
https://developers.facebook.com/docs/graph-api/securing-requests
I had to deal with the same issue while working with passport-facebook-token,
I finally released that the problem had nothing to have with the logic of my codebase or the app configuration.
I had this error just because I was adding intentionally an authorization Header to the request. so if you are using postman or some other http client just make sure that the request does not contain any authorization Header.

Categories