为您的rest flask应用程序提供hmac签名的简单集成。
flaskhmac的Python项目详细描述
此模块提供对烧瓶路由的身份验证预期的用例 用于restapi。它只是为了检查客户是否 根据实际情况,有权访问烧瓶应用程序中的特定路径 它必须拥有一把密匙。
用法
服务器
app=Flask(__name__)app.config['HMAC_KEY']='s3cr3tk3y'# define the secret key in an app config@app.route("/no_auth_view")defno_auth_view():return"no_auth_view"@app.route("/hmac_auth_view")@hmac.auth()# decorate viewdefhmac_auth_view():return"hmac_auth_view"@app.route("/hmac_auth_view")@hmac.auth(only=["foo"])# decorate view, only allows foo client accessdefhmac_auth_view():return"hmac_auth_view"
客户
无负载调用
sig=hmac.make_hmac()# generate signatureresponse=requests.get('/hmac_auth_view',headers={hmac.header:sig})
您还可以在不同的应用程序之间使用多个密钥。密钥是 作为字典存储在应用程序设置中的HMAC_KEYS中:
app.config['HMAC_KEYS']={'aservice':'akey','bservice':'bkey'}
然后必须使用make_hmac_for方法生成密钥
hmac.make_hmac_for('aservice',request_data)# data is optional# signature validation for multiple keyshmac.validate_service_signature(request)
带负载的调用
请求有效负载必须用作生成hmac的数据。
data=json.dumps({'foo':'boo'})sig=hmac.make_hmac(data)# generate signatureresponse=requests.post('/hmac_auth_view',data=data,headers={hmac.header:sig})
您可以定义覆盖abort方法的自定义错误:
classMyHmac(Hmac):defabort(self):message={'status':'403','message':'not authorized'}response=jsonify(message)response.status_code=403returnresponse
对于所有视图的hmac身份验证,您可以使用Flask'sbefore_request:
@app.before_requestdefbefore_request():try:hmac.validate_signature(request)exceptHmacException:returnabort(400)
为/从另一个应用程序生成签名:
sig=make_hmac(self,data,key=another_app_key)
更改日志
1.2.1
- 新的hmac_error_code配置选项,允许在失败时使用不同的http状态代码响应
1.2
- 中断更改:@hmac.auth现在需要将decorator调用为@hmac.auth()
- 新的参数仅用于@hmac.auth()仅允许特定客户端访问
1.1.2
- 交换urlsafe\u b64encode用于b64encode
1.1.1
- 支持多个键
0.1.1
- 能够在make\u hmac方法中更改密钥
- 方法验证签名已创建,可在hmac类之外使用
- 自定义异常
0.0.1
- 包括核心功能集的初始版本