Я отправляю запрос POST для регистрации на моем сайте.
Я использую PostMan, я получаю 200 ок
Я дважды отправляю запрос POST, использую пользовательские заголовки, я также получаю 200 ok
Когда я использую пакет python3 (запросы), я получаю 401.
Вот шаги:
Я определил функцию для вычисления md5 и пользовательских заголовков:
import re
import hashlib
def md5_utf8(x):
if isinstance(x, str):
x = x.encode('utf-8')
return hashlib.md5(x).hexdigest()
def make_digest_auth_headers(my_auth, uri):
nonce = re.findall(r'nonce="(.*?)"', my_auth)[0]
realm = re.findall(r'realm="(.*?)"', my_auth)[0]
qop = re.findall(r'qop="(.*?)"', my_auth)[0]
uri = uri
method = "POST"
nc = "00000001"
cnonce = "0a4f113b"
username = "my_user"
pwd = "my_pwd"
# cal HA1
HA1 = md5_utf8(username + ":" + realm + ":" + pwd)
# cal HA2
HA2 = md5_utf8(method + ":" + uri)
# cal client response
response = md5_utf8(HA1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + HA2)
headers = {
"Content-Type": "application/json;charset=utf-8",
"HOST": "ip:port",
"Accept": "application/json;charset=utf-8",
"Accept-Encoding": "gzip, deflate",
"Connection": "keep-alive",
"cache-control": "no-cache",
"Authorization": 'Digest username="' + username + '", realm="' + realm
+ '", nonce="' + nonce + '", uri="' + uri
+ '", algorithm=MD5, response="' + response + '", qop='
+ qop + ', nc=' + nc + ', cnonce="' + cnonce + '"'
}
return headers
Я отправил запрос POST, как это.
import requests
session = requests.Session()
session.headers = {
"Content-Type": "application/json;charset=utf-8",
"Accept": "application/json;charset=utf-8"
}
uri = "/System/Register"
data = {
"RegisterObject": {
"DeviceID": my_id
}
}
r = session.post('http://my_ip:my_port/System/Register', json=data)
headers = make_digest_auth_headers(r.headers['WWW-Authenticate'], uri)
r = self.session.post(f'{url}/VIID/System/Register', json=data, headers=headers)
print(r.json())
- Я получил 200 ок ответ
{'ResponseStatusObject': {'Id': 'my_id',
'LocalTime': '20190122090110',
'RequestURL': 'http://ip:port/System/Register',
'StatusCode': 0,
'StatusString': 'OK'}}
- Я использую python3-запросы:
import requests
from requests.auth import HTTPDigestAuth
session = requests.Session()
session.auth = HTTPDigestAuth(my_user, my_pwd)
session.headers = {
"Content-Type": "application/json;charset=utf-8",
"Accept": "application/json;charset=utf-8"
}
data = {
"RegisterObject": {
"DeviceID": my_id
}
}
session.post('http://ip:port/System/Register', json=data)
- Я получил 401:
{'ResponseStatusObject': {'Id': 'my_id',
'LocalTime': '20190122090110',
'RequestURL': 'http://ip:port/System/Register',
'StatusCode': 104,
'StatusString': 'Failed'}}
Не знаю почему? так странно.
Спасибо.