为您的rest flask应用程序提供hmac签名的简单集成。

flaskhmac的Python项目详细描述


circledownloadsversionlicense

此模块提供对烧瓶路由的身份验证预期的用例 用于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

  • 包括核心功能集的初始版本

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
在Java程序上运行Frida和JDB时出现问题   错误客户。java:12:错误:“(”或“[”预期客户a=新客户;   java为什么upcasting不显示运行时多态性?   键为枚举时java HashMap到SQL   为什么要在JavaEE安全中使用“领域”和“主体”的名称?   web应用程序Java Servlet 404错误   java Netbeans抛出NumberFormatException   在java中将arraylist传输到双数组[0]   JavaSpring安全性:如何停止记录拒绝访问异常   java使用ajax(跨域)向另一台服务器发送post请求,并使用jsp代码作为代理   java Android:导入featureModule与library模块上的资源   正则表达式来提取java源代码中的主类   浮点JAVA:两个浮点的差异