Django APIClient登录不起作用 [英] Django APIClient login not working
问题描述
我在单元单元测试中使用Django Rest Framework API进行身份验证时遇到问题.通过浏览器访问系统时,系统可以按预期工作.但是,在以下端点上向以下类发送放置请求时,我收到401 HTTP状态:
I'm having problem authenticating with my Django Rest Framework API in Unit Unit Tests. The system works as expected when accessing it through the browser. I however receive a 401 HTTP status when sending a put request to the following class at the following endpoint:
class UserDetail(RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin, GenericViewSet):
authentication_classes = (BasicAuthentication, TokenAuthentication)
permission_classes = IsAuthenticated,
queryset = CustomUser.objects.all()
serializer_class = UserSerializer
以下测试如下:
class AccountTests(APITestCase):
def setUp(self):
self.user = CustomUser.objects.create_user(email="user1@test.com", password="password1", is_staff=True)
self.user.save()
self.user = CustomUser.objects.get(email="user1@test.com")
self.client = APIClient()
def test_add_name(self):
self.client.login(email="user1@test.com", password='password1')
url = reverse('customuser-detail', args=(self.user.id,))
data = {'first_name': 'test', 'last_name': 'user'}
self.client.login(email="user1@test.com", password='password1')
response = self.client.put(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
在打印response.data时,我收到:
When printing the response.data, I receive:
{u'detail': u'Authentication credentials were not provided.'}
client.login(...)方法返回true,但是凭据似乎未附加到标头.我在IsAuthenticated权限类中的实验有一个request.user = AnonymousUser.在BasicAuthentication类中,auth = None.
The client.login(...) method returns true, but the credentials do not appear to be attached to the header. My experiments in the IsAuthenticated permission classes had an request.user = AnonymousUser. In the BasicAuthentication class, auth = None.
我是否缺少在settings.py中使用BasicAuth的某些信息?甚至在测试本身中?
Am I missing something as regards to using BasicAuth in settings.py? Or even in the test itself?
谢谢.
推荐答案
首先,当您提供"的凭证与模型不匹配时,会出现{u'detail': u'Authentication credentials were not provided.'}
. (我认为这是错误的错误消息)
First, {u'detail': u'Authentication credentials were not provided.'}
occurs when the credential that you "provide" doesn't match with models. (I think it is bad error message)
因此,由于加密,您应该通过set_password()
方法设置用户密码.
So, you should set user's password by set_password()
method, because of encryption.
self.user = CustomUser.objects.create_user(email="user1@test.com", is_staff=True)
self.user.set_password("password1")
self.user.save()
或者,您可以使用force_login()
进行测试.
or, you can use force_login()
for testing.
self.client.force_login(
user=User.objects.first(),
backend='django.contrib.auth.backends.ModelBackend' # one of your AUTHENTICATION_BACKENDS
)
这篇关于Django APIClient登录不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!