You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Django中使用Firebase认证时如何绕过DRF Token Authentication

问题原因

你当前的DRF全局配置强制所有接口默认走DRF Token认证,且要求访问用户为已认证状态,而Firebase登录接口本身是面向未登录用户开放的凭证获取接口,自然不能被全局的认证、权限规则拦截。

解决方案

1. 先放开登录接口的访问权限

在你的Auth视图类中单独指定空的认证类和权限类,覆盖全局配置,让登录接口可以被未认证用户直接访问:

class Auth(APIView):
    # 新增下面两行,单独关闭当前视图的认证和权限校验
    authentication_classes = []
    permission_classes = []
   
    def post(self, request, format=None):
        # 注意不要硬编码邮箱密码,改为从请求参数中获取
        email = request.data.get("email")
        password = request.data.get("password")
        if not email or not password:
            return Response({"error": "邮箱和密码不能为空"}, status=400)
        try:
            user = auth.sign_in_with_email_and_password(email, password)
        except Exception as e:
            return Response({"error": "账号或密码错误"}, status=401)
        return Response(user) 

2. 后续需要用Firebase idToken做接口认证的话,自定义DRF认证类

如果你后续其他接口需要校验用户携带的Firebase idToken是否有效,不能用默认的TokenAuthentication,需要自己实现认证逻辑:

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from django.contrib.auth.models import User

class FirebaseAuthentication(BaseAuthentication):
    def authenticate(self, request):
        # 从请求头获取Authorization: Bearer <idToken>
        auth_header = request.META.get('HTTP_AUTHORIZATION')
        if not auth_header or not auth_header.startswith('Bearer '):
            return None
        id_token = auth_header.split(' ')[1]
        try:
            # 校验idToken是否有效
            user_info = auth.get_account_info(id_token)
            firebase_uid = user_info['users'][0]['localId']
            # 这里可以根据业务需要,关联Django本地User表,或者直接返回自定义的用户对象
            # 示例:如果本地有对应用户就返回,没有就自动创建
            user, created = User.objects.get_or_create(username=firebase_uid, defaults={"email": user_info['users'][0]['email']})
            return (user, id_token)
        except Exception as e:
            raise AuthenticationFailed("无效的认证凭证")

3. 替换全局认证配置(可选)

如果你要所有接口默认走Firebase认证,修改settings.py中的DRF配置即可:

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": (
        # 替换为你自定义的Firebase认证类路径
        "你的应用名称.authentications.FirebaseAuthentication",
    ),
    "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",),
}

不需要全局配置的话,也可以按需把authentication_classes = [FirebaseAuthentication]加在需要认证的视图上。

内容的提问来源于stack exchange,提问作者siderra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 16:45:07