Django APIClient 登录不起作用

标签 django rest authentication frameworks apiclient

我在单元测试中使用我的 Django Rest Framework API 进行身份验证时遇到问题。通过浏览器访问时,系统按预期工作。但是,在以下端点向以下类发送放置请求时,我收到 401 HTTP 状态:

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 时,我收到:
{u'detail': u'Authentication credentials were not provided.'}

client.login(...) 方法返回 true,但凭据似乎没有附加到 header 。我在 IsAuthenticated 权限类中的实验有一个 request.user = AnonymousUser。在 BasicAuthentication 类中,auth = None。

我是否缺少有关在 settings.py 中使用 BasicAuth 的内容?或者甚至在测试本身?

谢谢。

最佳答案

一、{u'detail': u'Authentication credentials were not provided.'}当您“提供”的凭证与模型不匹配时发生。 (我认为这是错误的错误信息)

因此,您应该通过 set_password() 设置用户密码方法,因为加密。

self.user = CustomUser.objects.create_user(email="user1@test.com", is_staff=True)
self.user.set_password("password1")
self.user.save()

或者,您可以使用 force_login()用于检测。
self.client.force_login(
    user=User.objects.first(),
    backend='django.contrib.auth.backends.ModelBackend' # one of your AUTHENTICATION_BACKENDS
)

关于Django APIClient 登录不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37513050/

相关文章:

python - Django根据表单集中的其他两个字段计算字段

django - 如何自定义 Django 的 Flatpage 以在管理员的更改列表页面上显示新字段?

rest - API 休息 : 414 Request-URI too long using GET

javascript - 使用 AngularJs 从 PagedList(Web API) 获取集合中所有元素的数量

java - wowza authontication 使用外部 jar

python - 模块未找到错误 : No module named 'sklearn.neighbours'

python - 自定义查找未在 Django 中注册

Node.js 使用 socket.io 进行重构

javascript - 在 hapi.js 中,身份验证方案和策略有什么区别?

c# - ASP.NET/IIS : Log out all users