首页 > 解决方案 > 如何使用 Firebase 和 Django Rest 验证 ID 令牌?

问题描述

如果我使用 Firebase auth 并且我希望将其连接到我的 django rest 后端,我只是无法理解如何完成身份验证。

我使用getIdTokenResultfirebase提供的这样的:

 async login() {
            this.error = null;
            try {
                const response = await firebase.auth().signInWithEmailAndPassword(this.email, this.password);
                const token = await response.user.getIdTokenResult();

                /* 
                  No idea if this part below is correct 
                  Should I create a custom django view for this part?
                */

                 fetch("/account/firebase/", {
                     method: "POST",
                     headers: { 
                         "Content-Type": "application/json", 
                         "HTTP_AUTHORIZATION": token.token,
                     },
                     body: JSON.stringify({ username: this.email, password: this.password }),
                 }).then((response) => response.json().then((data) => console.log(data)));
            } catch (error) {
                this.error = error;
            }
        },

我在 firebase 文档中找到的唯一内容是这个乏味的两行代码段:https ://firebase.google.com/docs/auth/admin/verify-id-tokens#web

他们写的地方

decoded_token = auth.verify_id_token(id_token)
uid = decoded_token['uid']
# wtf, where does this go? 
# what do I do with this? Do I put it in a django View?

我在这里找到了将 django rest 连接到 firebase 的指南:https ://www.oscaralsing.com/firebase-authentication-in-django/

但我仍然不明白它是如何联系在一起的。我什么时候应该打电话给这个FirebaseAuthentication。每当我尝试调用该login函数时,我都会得到一个 403CSRF verification failed. Request aborted.

FirebaseAuthentication我在上面链接到的指南提供的整个课程 - 我应该将其添加为后端的路径吗?

path("firebase/", FirebaseAuthentication, name="api-firebase"),

我的前端调用的 api 端点是哪个?

标签: djangofirebasedjango-rest-frameworkfirebase-authentication

解决方案


推荐阅读