python requests 实现HTTPS双向SSL认证

程序界运粮官 2022-01-15 03:58:40 阅读数:259

Python Https requests 实现 双向

最近需要调用一个HTTPS接口,基于服务器CA证书、客户端client key、 client 证书的ssl双向认证连接。

原文链接
https://blog.csdn.net/weixin_51380973/article/details/113864819

- 网上了解到的实现是用python+urllib,

import urllib.request
import ssl
if __name__ == '__main__':
CA_FILE = "ca.crt"
KEY_FILE = "client.key"
CERT_FILE = "client.crt"
context = ssl.SSLContext(ssl.PROTOCOL_TLS)
context.check_hostname = False
context.load_cert_chain(certfile=CERT_FILE, keyfile=KEY_FILE)
context.load_verify_locations(CA_FILE)
context.verify_mode = ssl.CERT_REQUIRED
try:
# 通过request()方法创建一个请求:
request = urllib.request.Request('https://127.0.0.1:5000/')
res = urllib.request.urlopen(request, context=context)
print(res.code)
print(res.read().decode("utf-8"))
except Exception as ex:
print("Found Error in auth phase:%s" % str(ex))
  • 想用python+requests实现,但requests没有context参数,requests官网描述如下,

图1

图2
在这里插入图片描述

  • 用requests的cert+verify参数实现,连接成功,代码如下:
import requests
import ssl
if __name__ == '__main__':
try:
# 通过request()方法创建一个请求:
r=requests.get("https://127.0.0.1:5000/",cert=('client.crt','client.key'),verify='ca.crt')
print(r.status_code)
print(r.text)
print(r.headers)
except Exception as ex:
print("Found Error in auth phase:%s" % str(ex))

参考链接

https://blog.csdn.net/vip97yigang/article/details/84721027
https://2.python-requests.org/en/master/user/advanced/#ssl-cert-verification
https://blog.csdn.net/weixin_51380973/article/details/113864819

版权声明:本文为[程序界运粮官]所创,转载请带上原文链接,感谢。 https://blog.csdn.net/weixin_51380973/article/details/113864819