【问题标题】:Custom authentication backend not called with Django rest?没有使用 Django rest 调用自定义身份验证后端?
【发布时间】:2023-03-10 05:27:01
【问题描述】:

我正在尝试将 Firebase 用于我的 django rest / nuxt 项目,并且我需要在用户登录后验证 id 令牌 - 我只将 Firebase 用于身份验证部分。

我的自定义身份验证类如下所示:

class FirebaseAuthentication(authentication.BaseAuthentication):
    
    def authenticate(self, request, **kwargs):
        print("Why is this never called")
        auth_header = request.META.get("HTTP_AUTHORIZATION")

        if not auth_header:
            raise NoAuthToken("No auth token provided")

        id_token = auth_header.split(" ").pop()
        decoded_token = None
        try:
            decoded_token = auth.verify_id_token(id_token)
        except Exception:
            raise InvalidAuthToken("Invalid auth token")
            pass

        if not id_token or not decoded_token:
            return None

        try:
            uid = decoded_token.get("uid")
        except Exception:
            raise FirebaseError()

        
        user, created = User.objects.get_or_create(email=uid)

        user.profile.last_activity = timezone.localtime()
        return (user, None)

在我的settings.py 我得到了

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "firebase.authentication.FirebaseAuthentication",
    ),
}

views.py

@require_POST
def login_view(request):
    data = json.loads(request.body)
    email = data.get("email")
    password = data.get("password")
    
    
    
    if email is None or password is None:
        return JsonResponse({"detail": "Please provide email and password."}, status=400)

    user = authenticate(email=email, password=password)

    if user is None:
        return JsonResponse({"detail": "Invalid credentials."}, status=400)

    login(request, user)
    
    return JsonResponse({"detail": "Successfully logged in.", "isAuthenticated": True})

在我的 nuxt 应用上,登录:

async login() {
            this.error = null;
            try {
                const response = await firebase.auth().signInWithEmailAndPassword(this.email, this.password);
                const token = await response.user.getIdTokenResult();
                console.log(token.token);
                const res = await fetch("/account/login/", {
                    method: "POST",
                    headers: { 
                        "Content-Type": "application/json", 
                        "HTTP_AUTHORIZATION": token.token,
                        "X-CSRFToken": this.$store.getters.CSRFToken
                    },
                    credentials: "include",
                    mode: "cors",
                    body: JSON.stringify({ email: this.email, password: this.password }),
                });
                return await res.json()
            } catch (error) {
                this.error = error;
            }
        },

我到处都得到 200 - 用户在 firebase 和 django 方面都已登录,但 FirebaseAuthentication 没有被解雇。我错过了什么?

【问题讨论】:

    标签: firebase django-rest-framework firebase-authentication django-authentication


    【解决方案1】:

    你正在混合两个步骤

    1. 从 Firebase 获取 JWT 令牌
    2. 通过 django REST ("DEFAULT_AUTHENTICATION_CLASSES") 通过从步骤 1 中获取的 JWT 令牌对用户进行身份验证。

    这里不需要登录视图。你已经从前端做到了。

    现在你应该这样做;只需编写基于类的视图(更喜欢基于类的视图而不是基于函数的视图)。

    注意: authenticate 函数将在 REST_FRAMEWORK 字典下调用 AUTHENTICATION_BACKENDS 而不是 DEFAULT_AUTHENTICATION_CLASSES

    from rest_framework.permissions import IsAuthenticated
    
    class SampleProtectedAPIView(APIView):
        permission_classes = (IsAuthenticated,)  # Must include it to test user is authenticated 
        
        def post(self, request, *args, **kwargs):
            print(request.user) # will get user instance  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-01
      • 2015-07-31
      • 2017-10-27
      • 2017-01-07
      • 1970-01-01
      • 2017-10-16
      • 2015-12-26
      • 2021-02-06
      相关资源
      最近更新 更多