2

I have a Firebase Realtime Database with this data

Dummy data

And the security rules

{
  "rules": {
    ".read": "auth.uid != null",
    ".write": "auth.uid != null"
  }
}

In my react app, I track the current user in the application context that also uses onAuthStateChanged

    const [authUser, setAuthUser] = useState(null);

    ...

    const signIn = (email, password) => signInWithEmailAndPassword(firebaseAuth, email, password);

    const currUser = () => authUser;

    const authStateChange = authState => {
        if (!authState) setAuthUser(null);
        else {
            setAuthUser(authState);
        }
    }

    useEffect(() => {
        const unsubscribe = firebaseAuth.onAuthStateChanged(user => {
            authStateChange(user);
            setLoading(false);
        });

        return unsubscribe; // cleanup function on unmount
    }, []);

   ...

When a user signs in, this code runs to sign the user in with the authenticator

    const context = useAppContext();
    ...
    // handle form submit
    const handleSubmit = (event) => {
        event.preventDefault();
        const data = new FormData(event.currentTarget);
        context.signIn(data.get('email'), data.get('password'))
            .then(userCredential => {
                router.push('/');
            })
            .catch(err => { 
                console.log(JSON.stringify(err));
                setError({ code: err.code });
            });
    };

For actually accessing the database, I set up this code using axios to allow cross-origin access and using authToken params.


import axios from 'axios';

// create axios instance that sends to firebase rtdb 
const instance = axios.create({
    baseURL: process.env.NEXT_PUBLIC_FIREBASE_DB_URL, // firebase rtdb url
    headers: {
        'Access-Control-Allow-Origin': '*'
    }
});

// all requests require params since requests will need user ID token for authorization
const params = {
    authToken: null
}

export const getUser = async (id, authToken) => {
    params.authToken = authToken;
    return instance.get(`/users/${id}.json`, {
        params: params
    });
}

So when I actually put this all together and just get the one test data in users/test.json, I call the function to get the current user ID token with a forced refresh, then use the axios calls

    import { getUser } from "../lib/firebase/rtdb";

    ...

    const context = useAppContext();
    if (context.currUser()) {
        // add user to realtime database users document
        context.currUser().getIdToken(true)
            .then(idTokenString => {
                getUser('test', idTokenString).then(res => console.log(res.data));
            })
    }

Even after using a fresh token, I get a permission denied error (code 401).

Am I clearly doing something wrong?

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
Alex Marasco
  • 157
  • 3
  • 10
  • Have you tried `access_token` instead of `authToken` ? Also `console.log(params.authToken)` right before the Axios request to ensure the token is valid would help? – – Dharmaraj Apr 03 '22 at 18:49
  • @Dharmaraj `access_token` didn't work and logging it printed `eyJhbGciOiJSUzI1NiIsImtpZCI6IjQ2NDExN2FjMzk2YmM3MWM4YzU5ZmI1MTlmMDEzZTJiNWJiNmM2ZTEiLCJ0eXAiOiJKV1QifQ.eyJuYW1l...` I did notice that even with the refreshIdToken being called multiple times, it prints that same token. Could that be an issue? – Alex Marasco Apr 03 '22 at 18:51
  • Just to confirm, does this work when you paste the `https:///users/test.json?[TOKEN]` directly in browser? – Dharmaraj Apr 03 '22 at 18:56
  • @Dharmaraj `https:///users/test.json?authToken=[TOKEN]` does not work. Also, just checked, but I was wrong about the token not refreshing, it is – Alex Marasco Apr 03 '22 at 19:00
  • @Dharmaraj yes I did and it was an unauthorized request. I am copying and pasting all URLs and tokens directly from the console log to ensure they're correct. – Alex Marasco Apr 03 '22 at 19:07
  • 1
    I just recalled I had posted an [answer](https://stackoverflow.com/questions/68448750/firebase-realtime-rest-api-with-javascript) for similar issue where `access_token` didn't work either but the query param `?auth=TOKEN` did. Can you try this once (params.auth = theToken)? – Dharmaraj Apr 03 '22 at 19:10
  • @Dharmaraj auth worked for get. Seems to not work for PUT requests. – Alex Marasco Apr 03 '22 at 19:51
  • 1
    Just check if you still have authToken in put request... also try restarting the next js server – Dharmaraj Apr 03 '22 at 19:53
  • @Dharmaraj restarting next.js seems to have fixed it – Alex Marasco Apr 03 '22 at 20:01

1 Answers1

1

The working query parameter for passing UD token is actually "auth" and not "access_token" as in the documentation.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84