簡體   English   中英

使用標頭在 Django 測試客戶端中進行身份驗證

[英]Authenticate in Django test client with headers

我在我的 django 應用程序中覆蓋了ModelBackend 我的覆蓋模型后端要求在登錄用戶的請求中存在標頭。

HEADER = 'testing'
class TestingModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        testing_header_value = None
        if request is not None and request.META is not None:
            testing_header_value = request.META.get(HEADER, None)

        if username is None:
            username = kwargs.get(User.USERNAME_FIELD)
        try:
            user = User.objects.get_by_natural_key(username, testing_header_value)
        except User.DoesNotExist:
            # Run the default password hasher once to reduce the timing
            # difference between an existing and a nonexistent user (#20760).
            User().set_password(password)
        else:
            # now validate password and whether the user is active
            if user.check_password(password) and self.user_can_authenticate(user):
                return user

這在非測試場景中非常有效。 但是,當我測試時,我遇到了與測試客戶端傳遞標頭的問題。

Django 測試客戶端有一個登錄方法,但它在驗證時沒有傳遞request 這意味着我的模型后端無法正常運行 - 我無法傳遞我需要的標頭。 請注意, authenticate函數中的參數之一是當前請求。

我看到我可以使用force_login但這似乎有點 hack-y。 這樣做的正確方法是什么? 我懷疑對默認測試客戶端進行子類化並覆蓋login方法可能是最好的,但我不確定。

我相信force_login()是最適合您的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM