0

我試圖通過HTTP基本身份驗證登錄我的django-rest-framework測試客戶端以獲取REST-API標記。但不得不找出失敗一次,我隨機產生的用戶名和密碼太長:Python:長base64字符串無效的HTTP基本身份驗證標頭

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

原因是海峽.encode會自動將換行符添加到long base64字符串中。當您強制縮短輸入字符串時,代碼運行良好,例如uid = uuid.uuid4().hex[:28]

爲了避免它的更好的換行符使用:

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