Firebase admin getUser invalid grant - javascript

Verifying id token works without a problem, but strangely enough when I use firebaseAdmin.auth().getUser(uid) I get the following error:
FirebaseAppError: Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: invalid_grant (Invalid grant: account not found)". There are two likely causes: (1) your server time is not properly synced or (2) your certificate key file has been revoked. To solve (1), re-sync the time on your server. To solve (2), make sure the key ID for your key file is still present at https://console.firebase.google.com/iam-admin/serviceaccounts/project. If not, generate a new key file at https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk.
at C:\Users\dinop\Documents\VS Code\Personal\next_social_app\node_modules\firebase-admin\lib\app\firebase-app.js:85:19
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async getServerSideProps (webpack-internal:///./pages/user/[uid].tsx:30:30)
at async Object.renderToHTML (C:\Users\dinop\Documents\VS Code\Personal\next_social_app\node_modules\next\dist\server\render.js:506:20)
at async doRender (C:\Users\dinop\Documents\VS Code\Personal\next_social_app\node_modules\next\dist\server\base-server.js:708:34)
at async cacheEntry.responseCache.get.isManualRevalidate.isManualRevalidate (C:\Users\dinop\Documents\VS Code\Personal\next_social_app\node_modules\next\dist\server\base-server.js:813:28)
at async C:\Users\dinop\Documents\VS Code\Personal\next_social_app\node_modules\next\dist\server\response-cache\index.js:80:36 {
errorInfo: {
code: 'app/invalid-credential',
message: 'Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: invalid_grant (Invalid grant: account not found)". There are two likely causes: (1) your server time is not properly synced or (2) your certificate key file has been revoked. To solve (1), re-sync the time on your server. To solve (2), make sure the key ID for your key file is still present at https://console.firebase.google.com/iam-admin/serviceaccounts/project. If not, generate a new key file at https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk.'
},
codePrefix: 'app'
}
Just to clarify, this is a simple code snippet used in getServerSideProps:
const token = await firebaseAdmin.auth().verifyIdToken(cookies.token);
const pageUid: any = ctx.params?.uid;
console.log(pageUid); // gets printed, verifying id token works as explained.
const pageUserData = await firebaseAdmin.auth().getUser(pageUid); // throws the error
PageUid in this case exists just to be clear. I suspect it's a permission issue. The service account in use has the following permissions:
Firebase Admin SDK Administrator Service Agent
Firebase App Check Admin
Firebase Realtime Database Admin
Service Account Token Creator
Storage Admin

I generated a new Admin SDK key (even though I already had one), this solved the issue.

Related

firebase app check is not working with web client?

I have followed the official firebase app check installation tutorial:
https://firebase.google.com/docs/app-check/web/recaptcha-enterprise-provider
And I'm only getting errors.
I created and setup firebase project
Added app check library to my app
copy pasted app check initialization for web:
const appCheck = initializeAppCheck(firebaseApp, {
provider: new ReCaptchaEnterpriseProvider(
"my_recaptcha_key_here"
),
isTokenAutoRefreshEnabled: true, // Set to true to allow auto-refresh.
});
Enforced storage, enforced firestore from my console.
According to the tutorial, thats all you need to do.
RESULT:
Can't access anything from firestore, I get:
#firebase/app-check: FirebaseError: AppCheck: ReCAPTCHA error. (appCheck/recaptcha-error).
When uploading to storage, I get:
#firebase/app-check: FirebaseError: AppCheck: Fetch server returned an HTTP error status. HTTP status: 403. (appCheck/fetch-status-error).
Why is this happening, I have done all the steps in the tutorial?
Please make sure that the App URL is added to the reCAPTCHA allowed domains list.

Error: Credential is missing for AssociateSoftwareTokenCommand with AWS CognitoIdentityProviderClient Javascript SDK

BLUF: I would like to set up software token association in AWS Cognito in a user-facing JavaScript application (using AWS SDK) and am struggling with 'Credential is missing' errors.
I am trying to create an application using AWS Cognito using the Javascript SDK and the CognitoIdentityProviderClient that requires the user to use a software token MFA.
I can sign up and confirm the user using the SignUpCommand and I can generate a successful response for the user with InitiateAuthCommand using username/password login (first time logging in). At that point I then need to process an MFA_SETUP challenge which requires the use of a separate AssociateSoftwareTokenCommand flow to generate the secrets and responses.
I would expect to be able to let the end user, while logging in through their browser, issue the command to associate the software token themselves after successfully entering their username/password for the first time.
The problem I run in to is that I get the following error when issuing the AssociateSoftwareTokenCommand:
Error: Credential is missing
at SignatureV4.credentialProvider (runtimeConfig.browser.js:16)
at SignatureV4.<anonymous> (SignatureV4.js:169)
at step (tslib.es6.js:102)
at Object.next (tslib.es6.js:83)
at tslib.es6.js:76
at new Promise (<anonymous>)
at __awaiter (tslib.es6.js:72)
at SignatureV4.signRequest (SignatureV4.js:165)
at SignatureV4.<anonymous> (SignatureV4.js:85)
at step (tslib.es6.js:102)
Some vigorous Googling and looking through StackOverflow this method requires a credential object in the Client configuration, however this credential, as far as I can tell from Google/SO/AWS SDK docs, requires me to create an IAM object and generate keys / a secret key.
My application (built with React) is mostly single-app/browser based and I am trying to avoid additional server-side logic to act as a middleman if possible - and obviously don't want to go dropping secret keys into user-facing interfaces.
My questions then are:
Am I able to do this directly in my React App without action exposing credentials?
Is a server side middleman/proxy the only way for me to safely associate a software token?
Or is there perhaps some aspect of these credentials I am overlooking?
The offensive lines of code are simple (I can get the valid session key, no problem):
const client = new CognitoIdentityProviderClient({ region: AWS_REGION });
const command = new AssociateSoftwareTokenCommand({Session: session });
const response = await client.send(command)
Other searches have shown me that the credentials: {} object would then go in the client configuration object, which part I understand, I just don't want to put that on the client side with secret keys, etc.
Thank you for any assistance.

Firebase: How to handle invalid firebaseConfig passed to firebase.initializeApp()

I am having an angular app which connects to 2 firebase projects:
The default project is connected on app load via AngularFireModule.initializeApp(environment.firebaseConfig) (AngularFire2)
The secondary project is connected at run time via firebase.initializeApp(firebaseConfig, 'pr1'); (Firebase JS SDK)
Now the firebase config of the 2nd project is received from user through UI. So I need to validate if the firebase project exists with given credentials, before I could do any operation.
Calling res = firebase.initializeApp(firebaseConfig, 'pr1'); with invalid apiKey, authDomain, projectId, storageBucket, etc., is not throwing any error, but successfully returning a FirebaseAppImpl object.
After initialization, calling
res.auth()
res.storage()
also doesnt throw any errors but returning me proper objects.
Only for res.database(), I am getting a console warning as follows:
#firebase/database: FIREBASE WARNING: Firebase error. Please ensure that you spelled the name of your Firebase correctly (https://[invalid-url].firebaseio.com)
But its not throwing any errors, that I could act on.
I need to validate the given keys, and alert the user that 1 or more key is wrong. Any suggestions on how to do this?
Update 1:
Had a look at Firebase Management API: https://firebase.google.com/docs/projects/api/reference/rest
It has many functions like creating, retrieving projects.
But I am not sure, how to make use of any of these APIs to my requirement.

How do I listen to "_users" with PouchDB?

It seems like PouchDB doesn't allow me to listen to _users db, even if I'm logged in as admin.
I'm using socket-pouch and pouchdb-authentication to work with PouchDB. Firstly I'm logging in with pouchdb-authentication and then trying to subscribe to specified database with socket-pouch.
It works just fine for pretty much any ordinary database, but I'm keep getting 401 error when trying to sync with _users database, even if I'm logged in as admin:
Uncaught (in promise) n {error: "unauthorized", name: "unauthorized",
reason: "You are not a server admin.", message: "You are not a server
admin.", status: 401, …}
Is it possible to sync with _users database with PouchDB?
The _users database is easily accessible via curl, so my admin credentials are correct.
I have just omitted socket-pouch and it worked. It seems like that error is happening because of some socket-pouch bugs, not PouchDB itself.

IdentityServer3 and JWT ValidateIssuerSigningKey

I'm accessing a standard IdentityServer3 host app (ASP.NET WebApi 2).
I'm using the JavaScript way to get a token from IdSvr link
I then take that JWT add it to the authorisation request header and will attempt to process that in my app.
I use the: app.UseJwtBearerAuthentication middleware to validate this token. Firstly is this correct?
I have tried:
app.UseIdentityServerBearerTokenAuthentication(
new IdentityServerBearerTokenAuthenticationOptions
{
RequiredScopes = new[] { "myscope" },
IssuerName = "My Issuer"
});
But I get an error, "can't read token because it's not a valid base64 format".
With UseJwt... I get an error in our UAT environment about can't validate issuer signing key because I'm trying to use dev test one (which means I need the UAT cert). However, our other apps use app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()) and don't seem to have to worry about this issuer signing key....
Am I missing something in the way I'm trying to read and validate this token or shall I continue down my path with creating a X509SecurityKey() using the public key?
All our apps work with HTTPS so everything is communicated using TLS.
The recommended way is to set the Authority property to point to the identity server base URL. This way the certificate (amongst other things) is downloaded from the discovery document, and the middleware can configure itself automatically.

Categories