Python:带有长base64字符串

时间:2016-10-24 11:50:04

标签: python django base64 django-rest-framework http-basic-authentication

我尝试通过HTTP Basic身份验证登录我的django-rest-framework测试客户端以获取REST-API令牌。但是,一旦我的随机生成的用户名和密码太长,我必须发现它失败了:

def login_client(self):
    uid = uuid.uuid4().hex
    user = User.objects.create(username=uid, email="{}@foo.de".format(uid))
    user.set_password(uid)
    user.save()
    self.client.credentials(HTTP_AUTHORIZATION=self.get_knox_auth_header(uid, uid))
    response = self.client.post(reverse("knox_login"))
    print response.content.data["token"]

def get_knox_auth_header(self, username, password):
    return "Basic {}".format("{}:{}".format(username, password).encode("base64"))

标题看起来像:

Basic MTAyZDc2OTJjY2E5NGY0NmFmNThkODNmNDc5NTc6MTAyZDc2OTJjY2E5NGY0NmFmNThkODNmNDc5
NTc=

响应:

{"detail":"Invalid basic header. Credentials string should not contain spaces."}

1 个答案:

答案 0 :(得分:1)

原因是str.encode会自动为长base64字符串添加换行符。当您强制使用较短的输入字符串时,代码效果很好,例如uid = uuid.uuid4().hex[:28]

为避免换行,最好使用:

import base64
"Basic {}".format(base64.b64encode("{}:{}".format(username, password)))