Django中的urllib2 / pycurl:获取XML,检查HTTP状态,检查HTTPS连接 [英] urllib2/pycurl in Django: Fetch XML, check HTTP status, check HTTPS connection

查看:382
本文介绍了Django中的urllib2 / pycurl:获取XML,检查HTTP状态,检查HTTPS连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Django中进行API调用(作为我们需要的自定义认证系统的一部分)。用户名和密码通过SSL发送到特定的URL(对于这些参数使用GET),响应应为HTTP 200OK响应,主体包含用户信息的XML。

I need to make an API call (of sorts) in Django as a part of the custom authentication system we require. A username and password is sent to a specific URL over SSL (using GET for those parameters) and the response should be an HTTP 200 "OK" response with the body containing XML with the user's info.

对于不成功的身份验证,它将返回HTTP 401未经授权的响应。

On an unsuccessful auth, it will return an HTTP 401 "Unauthorized" response.

出于安全考虑,我需要检查:

For security reasons, I need to check:


  1. 请求通过HTTPS连接发送

  2. 服务器证书的公钥与预期值匹配(我使用'证书固定'以防止破坏的CA)

这是否可能在python / django中使用pycurl / urllib2或任何其他方法? p>

Is this possible in python/django using pycurl/urllib2 or any other method?

推荐答案

使用 M2Crypto

from M2Crypto import SSL
ctx = SSL.Context('sslv3')
ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, depth=9)
if ctx.load_verify_locations('ca.pem') != 1:
   raise Exception('No CA certs')

c = SSL.Connection(ctx)
c.connect(('www.google.com', 443)) # automatically checks cert matches host
c.send('GET / \n')
c.close()

使用 urllib2_ssl (不言而喻,但要明确使用:风险自负):

Using urllib2_ssl (it goes without saying but to be explicit: use it at your own risk):

import urllib2, urllib2_ssl

opener = urllib2.build_opener(urllib2_ssl.HTTPSHandler(ca_certs='ca.pem'))
xml = opener.open('https://example.com/').read()

相关:使HTTPS请求在Python中安全

使用 pycurl

c = pycurl.Curl()
c.setopt(pycurl.URL, "https://example.com?param1=val1&param2=val2")
c.setopt(pycurl.HTTPGET, 1)
c.setopt(pycurl.CAINFO, 'ca.pem')
c.setopt(pycurl.SSL_VERIFYPEER, 1)
c.setopt(pycurl.SSL_VERIFYHOST, 2)
c.setopt(pycurl.SSLVERSION,     3)    
c.setopt(pycurl.NOBODY, 1)
c.setopt(pycurl.NOSIGNAL, 1)
c.perform()
c.close()

要实施'证书固定'提供不同的 'ca.pem'为不同的域。

To implement 'certificate pinning' provide different 'ca.pem' for different domains.

这篇关于Django中的urllib2 / pycurl:获取XML,检查HTTP状态,检查HTTPS连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆