[英]Django Rest Framework JWT Authentication Test
I'm setting up DRF to work with JWT Token Authentication. 我正在设置DRF以与JWT令牌认证一起使用。 I seem to be at a point that DRF-JWT says that it's working correctly, but I can't get a login test to successfully run. 我似乎要说DRF-JWT说它可以正常工作,但是我无法获得成功运行的登录测试。
I've gone through the installation steps in the django-rest-framework-jwt docs and I am able to successfully run the curl $ curl -X POST -d "username=admin&password=abc123" http://localhost:8000/api-token-auth/
and get back a token. 我已经完成了django-rest-framework-jwt文档中的安装步骤,并且能够成功运行curl $ curl -X POST -d "username=admin&password=abc123" http://localhost:8000/api-token-auth/
并获取令牌。
I am expecting my test to pass me back a token as well, but apparently I don't have it set up right. 我希望我的考试也能通过令牌,但显然我没有正确设置令牌。
# tests.py
class LoginTests(APITestCase):
def setUp(self):
self.user = NormalUserFactory.create()
self.jwt_url = reverse('jwt_login')
def test_token_get_not_allowed(self):
# do not allow GET requests to the login page
response = self.client.get(self.jwt_url)
self.assertEqual(response.data.get('detail'), 'Method "GET" not allowed.')
def test_token_login_fail_incorrect_credentials(self):
# pass in incorrect credentials
data = {
'username': self.user.username,
'password': 'inCorrect01'
}
response = self.client.post(self.jwt_url, data)
self.assertEqual(response.data.get('non_field_errors'),
['Unable to login with provided credentials.'])
def test_token_login_success(self):
data = {
'username': self.user.username,
'password': 'normalpassword',
}
response = self.client.post(self.jwt_url, data)
print(response.data.get("token"))
self.assertNotEqual(response.data.get("token"), None)
The first two unittests run successfully, but the third will not return the token, but instead returns {'non_field_error':'Unable to login with provided credentials.'}
, what I'm expecting when the credentials are incorrect. 前两个单元测试成功运行,但是第三个单元测试不会返回令牌,而是返回{'non_field_error':'Unable to login with provided credentials.'}
,这是我期望的凭据不正确的情况。
To create the User instance (and other model instances) I am using factory_boy. 要创建用户实例(和其他模型实例),我正在使用factory_boy。 This same method to create instances works in other apps within this project, as well as other projects, and I have verified the user does exist in the test database. 创建实例的相同方法可在该项目内的其他应用程序以及其他项目中使用,并且我已验证用户确实存在于测试数据库中。
# factories.py
class UserFactory(DjangoModelFactory):
class Meta:
model = User
native_language = 'es'
class NormalUserFactory(UserFactory):
username = 'normaluser'
password = 'normalpassword'
email = 'user@email.com'
first_name = 'John'
last_name = 'Doe'
here are my relevant settings as well: 这也是我的相关设置:
# settings.py
REST_FRAMEWORK = {
'API_ROOT': '/v1/',
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
}
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=14)
}
Try the following code: 尝试以下代码:
class LoginTests(APITestCase):
def setUp(self):
self.user = NormalUserFactory.create()
self.jwt_url = reverse('jwt_login')
def test_post_form_failing_jwt_auth(self):
"""
Ensure POSTing form over JWT auth without correct credentials fails
"""
data = {
'username': self.user.username,
'password': 'inCorrect01'
}
response = self.client.post(self.jwt_url, data)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.