本文主要是介绍处理https中的Digest authentication鉴权,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题:
RESTful 的传输协议类型为 HTTPS,鉴权方式为 Digest_SHA256(即DIGEST摘要认证) 时,接口调用问题。
参考资料:
-
认识HTTP摘要认证: https://www.cnblogs.com/xiaoxiaotank/p/11078571.html
-
requests提供的身份认证处理方法:https://cn.python-requests.org/zh_CN/latest/user/authentication.html
普通的RESTful接口调用:
import requests
from requests.auth import HTTPDigestAuth# 设置密码
def change_password(cur_ip):payload = {"ManipulateName": "ApiAdmin","ManipulatePwd": "HuaWei123","ManipulateModule": 3,"ManipulateInfo": {"UserName": "ApiAdmin","UserPwd": "HuaWei1234"}}username = 'ApiAdmin'password = 'HuaWei1234'# 因为相机只提供了https协议url = 'https://{}/SDCAPI/V1.0/AuthIaas/Users'.format(cur_ip)res = requests.put(url=url,headers=headers,# 使用摘要认证# HTTPDigestAuth内部自动根据接口返回区分处理SHA256、MD5加密方式auth=HTTPDigestAuth(username, password),data=payload,timeout=5)print(res.text)
代码存在的问题:
因为requests的请求默认开启了验证服务器TLS证书的开关,导致程序不会用摘要认证HTTPDigestAuth方法对接口返回的401进行处理。![在这里插入图片描述](https://img-blog.csdnimg.cn/9be5f412b1ee4f43a50680dbdf77a136.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAUXJlZHN1bg==,size_20,color_FFFFFF,t_70,g_se,x_16
解决方法:
在put方法中增加参数:verify=False
,关闭验证服务器TLS证书的开关。
同理:
如果RESTful 的传输协议类型为 HTTP,鉴权方式为 Digest_SHA256(即DIGEST摘要认证) 时,接口调用的代码:
import requests
from requests.auth import HTTPDigestAuth# 设置密码
def change_password(cur_ip):payload = {"ManipulateName": "ApiAdmin","ManipulatePwd": "HuaWei123","ManipulateModule": 3,"ManipulateInfo": {"UserName": "ApiAdmin","UserPwd": "HuaWei1234"}}username = 'ApiAdmin'password = 'HuaWei1234'# 使用http协议url = 'http://{}/SDCAPI/V1.0/AuthIaas/Users'.format(cur_ip)res = requests.put(url=url,headers=headers,auth=HTTPDigestAuth(username, password),data=payload,timeout=5)print(res.text)
如果RESTful 的传输协议类型为 HTTPS,鉴权方式为 Digest_MD5(即DIGEST摘要认证) 时,接口调用的代码可以是:
import requests
from requests.auth import HTTPDigestAuth# 设置密码
def change_password(cur_ip):payload = {"ManipulateName": "ApiAdmin","ManipulatePwd": "HuaWei123","ManipulateModule": 3,"ManipulateInfo": {"UserName": "ApiAdmin","UserPwd": "HuaWei1234"}}username = 'ApiAdmin'password = 'HuaWei1234'url = 'https://{}/SDCAPI/V1.0/AuthIaas/Users'.format(cur_ip)res = requests.put(url=url,headers=headers,auth=HTTPDigestAuth(username, password),data=payload,# 关闭SSL认证verify=False,timeout=5)print(res.text)
这篇关于处理https中的Digest authentication鉴权的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!