我正在尝试将TokenAuthentication与我的一个视图一起使用.如https://www.django-rest-framework.org/api-guide/authentication/中所述,我将登录时收到的令牌添加为我发送的请求中称为"授权"的HTTP头.
问题是在我的单元测试中,身份验证失败了.查看TokenAuthentication类,我看到正在检查的标头是'HTTP_AUTHORIZATION'而不是'授权'
我正在使用的视图:
class DeviceCreate(generics.CreateAPIView):
model = Device
serializer_class = DeviceSerializer
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
Run Code Online (Sandbox Code Playgroud)
将标题更改为"HTTP_AUTHORIZATION"似乎有效,但感觉不对.
我错过了什么吗?
django authorization django-rest-framework http-token-authentication
大家.我正在尝试使用带有http basic auth的django-tastypie为RESTful API编写测试.所以,我有以下代码:
def http_auth(username, password):
credentials = base64.encodestring('%s:%s' % (username, password)).strip()
auth_string = 'Basic %s' % credentials
return auth_string
class FileApiTest(TestCase):
fixtures = ['test/fixtures/test_users.json']
def setUp(self):
self.extra = {
'HTTP_AUTHORIZATION': http_auth('testuser', 'qwerty')
}
def test_folder_resource(self):
response = self.client.get('/api/1.0/folder/', **self.extra)
self.assertEqual(response.status_code, 200)
def test_folder_resource_post(self):
response = self.client.post('/api/1.0/folder/', **self.extra)
self.assertNotEqual(response.status_code, 401)
Run Code Online (Sandbox Code Playgroud)
GET请求完成,返回状态代码200.但POST请求总是返回401.我确信我做错了.有什么建议?