Python: 无效的 HTTP 基本身份验证 header 长 base64 字符串

Python: Invalid HTTP basic authentication header with long base64 string

我试图通过 HTTP 基本身份验证登录我的 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"))

Header 看起来像:

Basic MTAyZDc2OTJjY2E5NGY0NmFmNThkODNmNDc5NTc6MTAyZDc2OTJjY2E5NGY0NmFmNThkODNmNDc5
NTc=

回复:

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

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

为了避免换行,最好使用:

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