Skip to content

[with-firebase-authentication] Can't use Firebase Admin SDK for anything other than verifying the token #14139

Description

@tomthornton

Bug report

Describe the bug

There's a problem with the credential in initializing the firebase admin app. It works perfectly with admin.verifyToken, but any other method I try to use yields an error of

Error: 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.

I've tried everything. Is there no way to use the firebase admin SDK with anything else in NextJS?

To Reproduce

firebaseAdmin.js

import * as admin from 'firebase-admin'

export const createUser = (email) => {
const firebasePrivateKey = process.env.FIREBASE_PRIVATE_KEY

if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.cert({
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
// https://stackoverflow.com/a/41044630/1332513
privateKey: firebasePrivateKey.replace(/\n/g, '\n'),
}),
databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
})
}

return admin.auth().createUser({
email: 'example@test.com',
password: 'password'
})
}

export const verifyIdToken = (token) => {
const firebasePrivateKey = process.env.FIREBASE_PRIVATE_KEY
if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.cert({
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
// https://stackoverflow.com/a/41044630/1332513
privateKey: firebasePrivateKey.replace(/\n/g, '\n'),
}),
databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
})
}

return admin
.auth()
.verifyIdToken(token)
.catch((error) => {
throw error
})
}

Try to run createUser from an API endpoint

Expected behavior

It should just work. I need a custom flow for creating my users.

System information

  • Mac.OS
  • Node '12.16.1'
  • NextJS - latest

Metadata

Metadata

Assignees

No one assigned

    Labels

    examplesIssue was opened via the examples template.good first issueEasy to fix issues, good for newcomerslockedstaleThe issue has not seen recent activity.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions