在 Django 中使用 Firebase 身份验证 [英] Using Firebase Auth with Django

查看:27
本文介绍了在 Django 中使用 Firebase 身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对我的 django webapp 使用 firebase 身份验证.为了实现这一点,我想我是否需要编写一个自定义身份验证后端 - 是吗?我没有看到任何已经这样做的库 - django-allauth 看起来非常接近作为替代方案,但我对 firebase 提供的电话号码验证感兴趣.

I want to use firebase authentication for my django webapp. To achieve this, I think would I need to write a custom auth backend - is that right? I don't see any libraries that already do this - django-allauth looks like it comes pretty close as an alternative but I am interested in the phone number verification provided by firebase.

我也对 User 模型和 request.useruser.is_authenticated 等函数会发生什么感到困惑.现在我使用身份验证和登录功能 - django 如何知道用户是通过 firebase 登录的?我还会为每个用户创建一个用户模型吗?

I'm also confused about what happens to the User model and functions like request.user or user.is_authenticated. Right now I use the authenticate and login functions - how does django know that a user is logged in via firebase? Would I still be creating a User model for every user?

谢谢

推荐答案

您可以将 Firebase 身份验证与任何框架一起使用.您不一定需要使用自定义身份验证.通常,您会在客户端上登录用户,通过调用 firebase.auth().currentUser.getIdToken() 获取 ID 令牌,然后将 ID 令牌传递给您的服务器,对其进行验证并解析使用 Firebase Admin SDK 识别用户 ID 及其其他声明的有效负载,然后您可以发出会话 cookie,识别与该 ID 令牌关联的用户.

You can use Firebase Auth with any framework. You don't necessarily need to use custom auth. Typically, you would sign in the user on the client, get the ID token by calling firebase.auth().currentUser.getIdToken() and then pass the ID token to your server, verify it and parse its payload identifying the user ID and its other claims by using the Firebase Admin SDKs and then you can issue a session cookie identifying the user associated with that ID token.

在退出时,您将清除该会话 cookie.

On signout, you would clear that session cookie.

如果您还需要在设置会话 cookie 后将该用户保留在后端,您还可以使用 Firebase Admin SDK 查找由用户 ID 标识的用户,或者仅使用令牌声明来填充没有任何网络的用户称呼.如果需要,您可以在关联框架的用户模型中填充它.

If you also need to persist that user on the backend after setting the session cookie, you can also use the Firebase Admin SDK to lookup a user identified by the user ID or just use the token claims to populate the user without any network call. You can populate that in the user model of associated framework if needed.

有关会话管理的更多信息,您可以参考此 django 文档:https://docs.djangoproject.com/en/3.0/topics/http/sessions/

For more on session management, you can refer to this django documentation: https://docs.djangoproject.com/en/3.0/topics/http/sessions/

这篇关于在 Django 中使用 Firebase 身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆