【问题标题】:Authentication using Django Rest + JWT during tests在测试期间使用 Django Rest + JWT 进行身份验证
【发布时间】:2018-07-13 21:22:06
【问题描述】:

这里的问题。我无法使用 DRF + JWT 测试我的登录功能。在测试环境之外一切正常,我可以使用完全相同的方法以管理员身份登录并取回我的令牌。

from django.test import TestCase
from django.contrib.auth.models import User

from rest_framework.test import RequestsClient




TEST_USER = {
    'username': 'test1',
    'email': 'test@test.com',
    'password': 'qwe123qwe',
}
BASE_URL = 'http://testserver/'
API_LOGIN = 'http://testserver/' + 'api-token-auth/'


class TestAuthentication(TestCase):
    def setUp(self):
        User.objects.create(**TEST_USER)
        self.requests = RequestsClient()

    def test_user_can_login(self):
        user = User.objects.first()
        self.assertEqual(User.objects.count(), 1)
        response = self.requests.post(API_LOGIN, TEST_USER)
        print(response.content)

输出是:

b'{"non_field_errors":["使用提供的无法登录 证书。”]}' .. -------------------------------------------------- -------------------- 在 0.018 秒内运行 2 次测试

我真的很想在我的测试中包含登录/注销,因为它是我项目的基础。如果我可以提供任何可以帮助您帮助我的更多信息,请发表评论,我会一直关注这个帖子,直到它解决为止,我没有更好的事情可做:)

编辑:

似乎问题与测试无关......

>>> from django.contrib.auth.models import User
>>> User.objects.create(username="test1", password="qwe123qwe")
>>> r = post("http://127.0.0.1:8000/api-token-auth/", data={'username': 'test1', 'password': 'qwe123qwe'})
>>> r
<Response [400]>
>>> r.content
b'{"non_field_errors":["Unable to log in with provided credentials."]}'

对于超级用户(manage.py createsuperuser)它工作正常

>>> r = post("http://127.0.0.1:8000/api-token-auth/", data={'username': 'root', 'password': 'qwe123qwe'})
>>> r.content
b'{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6InJvb3QiLCJleHAiOjE1MTc2NzQ4OTMsImVtYWlsIjoid0B3LnBsIn0.hox4-aggdWB5xG0HNe3vUeVAiVZTPbqe373fdVaERWI"}' 

【问题讨论】:

    标签: python django unit-testing django-rest-framework jwt


    【解决方案1】:

    好吧,如果有人关心问题是我使用的是

    User.objects.create().
    

    创建用户的正确方法是

    User.objects.create_user()
    

    【讨论】:

    • 关于为什么需要这样做的额外信息:create_userUser 对象上使用set_password 方法(对密码进行哈希处理)。简单的create 将不起作用,因为密码将按原样存储(无散列),然后使用该密码登录将尝试将输入密码的散列与原始存储的密码相匹配,这显然不会匹配。
    【解决方案2】:

    我正在使用 django rest token 并使用它进行测试

    from rest_framework.test import APIClient
    
    # get token
    temp = APIClient()
    data = {"username": "testuser", "password": "abc"}
    resp = temp.post("/token-auth/", data=data, follow=True)
    token = resp.data["token"]
    
    # authenticate using the token header on other API
    temp.credentials(HTTP_AUTHORIZATION='Token ' + token)
    resp = temp.get("/getMyItems")
    print("resp: " + str(resp))
    

    【讨论】:

      猜你喜欢
      • 2015-06-01
      • 2019-05-02
      • 2023-03-31
      • 2018-12-15
      • 2013-12-29
      • 2019-01-01
      • 2016-01-09
      • 2016-12-16
      • 2015-04-11
      相关资源
      最近更新 更多