macauth
项目描述
这是一个实现MAC访问认证的低级库,这是一个在
http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01中描述的简单HTTP请求签名方案。
要使用MAC访问认证访问资源,客户端必须获得一组MAC凭证,包括ID和密钥。他们使用这些凭证向服务器发送签名请求。
访问受保护资源时,服务器将生成一个带有“MAC”方案的401挑战响应,如下所示
> GET /protected_resource HTTP/1.1 > Host: example.com < HTTP/1.1 401 Unauthorized < WWW-Authenticate: MAC
客户端将使用他们的MAC凭证构建请求签名,并将其包含在Authorization头中,如下所示
> GET /protected_resource HTTP/1.1 > Host: example.com > Authorization: MAC id="h480djs93hd8", > ts="1336363200", > nonce="dj83hs9s", > mac="bhCQXTVyfj5cmA9uKkPFx1zeOXM=" < HTTP/1.1 200 OK < Content-Type: text/plain < < For your eyes only: secret data!
该库提供了实现此类认证方案所需的底层函数。对于MAC认证客户端,它提供了以下功能
sign_request(req, id, key, hashmod=sha1): 使用MAC访问认证签名请求。
对于MAC认证服务器,它提供了以下函数
get_id(req): 从请求中获取声明的MAC认证ID。
check_signature(req, key, hashmod=sha1): 检查请求是否使用给定密钥签名。
传递给这些函数的请求对象可以是各种常见对象类型之一
一个WSGI环境字典
一个webob.Request对象
一个requests.Request对象
请求数据的字符串或文件对象
客户端程序的典型用途可能是将sign_request函数安装为认证钩子,当使用requests库时,如下所示
import requests import functools import macauthlib # Hook up sign_request() to be called on every request. def auth_hook(req): macauthlib.sign_request(req, id="<AUTH-ID>", key="<AUTH-KEY>") return req session = requests.session(hooks={"pre_request": auth_hook}) # Then use the session as normal, and the auth is applied transparently. session.get("http://www.secret-data.com/get-my-data")
服务器程序的典型用途可能是使用WSGI中间件组件验证请求,如下所示
class MACAuthMiddleware(object): # ...setup code goes here... def __call__(self, environ, start_response): # Find the identity claimed by the request. id = macauthlib.get_id(environ) # Look up their secret key. key = self.SECRET_KEYS[id] # If the signature is invalid, error out. if not macauthlib.check_signature(environ, key): start_response("401 Unauthorized", [("WWW-Authenticate", "MAC")]) return [""] # Otherwise continue to the main application. return self.application(environ, start_response)
0.6.0 - 2013-06-25
支持requests版本1.0.0及以上;感谢bobbyrward。遗憾的是,这与requests的旧版本不兼容。
0.5.0 - 2012-11-26
通过源级兼容性支持Python 3。
0.4.0 - 2012-09-31
允许主API函数接受WebOb请求对象、requests请求对象或WSGI环境字典作为第一个参数。这应该有助于实现客户端程序。
macauthlib.sign_request()现在返回Authorization头值,如果您将其作为要签名的请求传递不可变对象时很有用。
隐藏macauthlib.utils中之前直接从macauthlib可用的函数。这将确保用户从规范位置导入它们。
0.3.0 - 2012-07-11
简化NonceCache类的API;现在它提供了一个单一的check_nonce()方法,而不是单独的is_fresh()和add_nonce()方法。
0.2.0 - 2012-06-01
修复NonceCache中的竞争条件错误。
0.1.0 - 2012-02-27
初始发布。