django rest框架的http签名支持
djangorestframework-httpsignature的Python项目详细描述
Overview
为Django REST framework提供HTTP Signature支持。http签名包提供了一种实现http消息的源身份验证和消息完整性的方法。类似于亚马逊的HTTP Signature scheme,被亚马逊的许多服务所使用。HTTP Signature规范目前是ietf草案。
Installation
通过存储库安装软件包:
pip install djangorestframework-httpsignature
较旧版本的pip不支持轮盘格式(这就是httpsig的分发方式)。安装需求时出现问题,pip将抱怨找不到httpsig。在这种情况下,pip需要升级:
pip install --upgrade pip
另一个可能的问题:通过python setup.py install安装时,可能会遇到:
No local packages or download links found for httpsig error: Could not find suitable distribution for Requirement.parse('httpsig')
如果是这样,请使用pip install httpsig安装httpsig包,然后重试python setup.py install。
Usage
要通过http签名验证http请求,您需要:
按照Installation中的说明,在django项目中安装此包。
将rest_framework_httpsignature添加到已安装的settings.py应用程序中。
在应用程序代码中,扩展SignatureAuthentication类,如下所示:
# my_api/auth.py from rest_framework_httpsignature.authentication import SignatureAuthentication class MyAPISignatureAuthentication(SignatureAuthentication): # The HTTP header used to pass the consumer key ID. # Defaults to 'X-Api-Key'. API_KEY_HEADER = 'X-Api-Key' # A method to fetch (User instance, user_secret_string) from the # consumer key ID, or None in case it is not found. def fetch_user_data(self, api_key): # ... # example implementation: try: user = User.objects.get(api_key=api_key) return (user, user.secret) except User.DoesNotExist: return None
配置django rest框架以使用身份验证类;例如:
# my_project/settings.py # ... REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'my_api.auth.MyAPISignatureAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } # The above will force HTTP signature for all requests. # ...
Roadmap
- 目前,库只支持hmac sha256进行签名。
- REQUIREMENTS.txt文件相当严格。很有可能以前的django和django rest框架版本是受支持的。
- 由于http签名对请求日期和时间使用http头,身份验证类可以处理请求到期。
Example usage & session w/cURL
假设在Usage中详细介绍了设置,那么可以使用curl探测在localhost:8000上运行的项目,如下所示:
~$ SSS=Base64(Hmac(SECRET, "Date: Mon, 17 Feb 2014 06:11:05 GMT", SHA256)) ~$ curl -v -H 'Date: "Mon, 17 Feb 2014 06:11:05 GMT"' -H 'Authorization: Signature keyId="my-key",algorithm="hmac-sha256",headers="date",signature="SSS"'
对于一个不那么痛苦的例子,请查看httpsig package文档以使用requests和httpsig。