Home > Software design >  Firebase Auth Permission Denied After Refreshing Token
Firebase Auth Permission Denied After Refreshing Token

Time:04-04

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?

CodePudding user response:

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

  • Related