刷新令牌后 Firebase 身份验证权限被拒绝

发布于 2025-01-18 15:36:21 字数 2707 浏览 1 评论 0原文

我有一个带有此数据的firebase实时数据库

“虚拟数据”

以及我的React应用程序中的安全规则

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

,我在应用程序上下文中跟踪当前用户,

    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
    }, []);

   ...

当用户登录时,该代码运行以签名以签名在使用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 });
            });
    };

实际访问数据库的情况下,我使用Axios设置此代码,以允许交叉访问和使用Authtoken参数。


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
    });
}

当我实际上将所有这些放在一起并在用户/test中获取一个测试数据时。

    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));
            })
    }

因此, 我获得了拒绝错误的权限(代码401)。

我显然做错了吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

抱猫软卧 2025-01-25 15:36:21

传递UD代币的工作查询参数实际上是“ auth”的,而不是文档

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文