【问题标题】:How to test successful token claim with jwt如何使用 jwt 测试成功的令牌声明
【发布时间】:2020-11-02 02:49:54
【问题描述】:

我正在使用 django rest simple jwt,我想测试一个简单的登录并检查令牌的响应数据和其他自定义数据。

所以我尝试使用 APITestCase 创建用户,然后尝试使用相同的凭据登录。

结果是 401 而不是 200,响应数据中带有标记。

这是我的简化测试用例:

from rest_framework.test import APITestCase
from django.contrib.auth import get_user_model

# Create your tests here.
User = get_user_model()

class UserAuthTestCase(APITestCase):
    username = "someuser"
    password = "1234pass"


    def setUp(self):
        self.user = User.objects.create(
            username=self.username,
            password=self.password
        )

    def test_successful_login_gives_200(self):
        response = self.client.post(
            '/auth/token/',
            {
                'username': self.username,
                'password': self.password
            },
            format='json'
        )
        self.assertEqual(response.status_code, 200)

其余框架配置设置为仅使用simplejwt身份验证。

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
}

【问题讨论】:

    标签: python django django-rest-framework django-testing django-rest-framework-simplejwt


    【解决方案1】:

    使用User.objects.create 创建User 时,您设置的密码没有散列,因此当您稍后尝试对用户进行身份验证时,您最终会将散列密码值与原始未散列密码进行比较数据库。使用User.objects.create_user,它通过在内部调用set_password 来处理散列。

    【讨论】:

    猜你喜欢
    • 2021-04-30
    • 2019-06-22
    • 2016-12-23
    • 2020-01-23
    • 2017-02-13
    • 2020-10-23
    • 2016-04-30
    • 2021-02-13
    • 1970-01-01
    相关资源
    最近更新 更多