'Firebase Security Rules: Pass custom UID in request.auth without Firebase Authentication
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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Doug Stevenson |
