2

I'm using next-auth v4, Firebase v9 and NextJS and trying to solve an issue with Firebase security rules.

My security rules do not receive anything in request.auth because I'm using next-auth and I couldn't find a way to pass my next-auth session ID as a UID in firebase requests.

In next-auth, I'm using session callbacks to determine when to create new user in database:

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  secret: process.env.JWT_SECRET,
  callbacks: {
    async session({ session, token }) {
      session.id = token?.sub;

      const userDocRef = doc(db, "users", session.id);
      const userDocSnap = await getDoc(userDocRef);

      if (!userDocSnap.exists()) {
        await setDoc(doc(db, "users", session.id), {
          uid: session.id,
          name: session.user.name,
          image: session.user.image,
          email: session.user.email,
        });
      }

How can I make it so that I'm able to verify the userId from the firebase side, while still using next-auth. Is there a way to pass session.id from my JWT to firebase?

1 Answer 1

2

In the documentation it states:

If your app uses Firebase Authentication or Google Cloud Identity Platform, the request.auth variable contains the authentication information for the client requesting data.

Firebase security rules only receive user information when using Firebase Authentication or Google Cloud Identity. It cannot be made to work with other auth systems. The UID of the currently signed in user is always provided securely by the Firebase SDK. There is no way to "pass" a UID into security rules - that would not be secure at all, as it would be easy to fake the user.

Perhaps you could use some sort of custom authentication implementation of your creation to bridge between what you have now and Firebase. You will still need to use the Firebase Auth SDK to sign the user in.

Sign up to request clarification or add additional context in comments.

2 Comments

What if instead of using security rules, I just add a check in the API that if the UID of the user exists in JWT and also in the database and let the user modify the database, otherwise don't. Is this good security wise? or are there any downsides to this?
Client code isn't secure since you don't control the machine where it executes. A malicious user can execute whatever code they want. That's why security rules are managed on the backend using a JWT that's also provided by the backend.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.