效果
对于flask-restplus框架,本身集成了swagger api页面,那么如何在swagger页面当中显示一个“Authorize”模块呢,如下图所示:
点击Authorize按钮弹出窗中可以输入Username和Password
方案
事实上,我们在申明api对象的时候是可以指定Authoritarian的方式的,然后启动主程序即可:
# 以下为Basic验证举例
# 先声明一个authorizations对象,是一个字典
authorizations = {
'Basic Auth': {
'type': 'basic',
'in': 'header',
'name': 'Authorization'
},
}
# 申明Api对象,并传入secucrity类型和authorization参数
api = Api(
blueprint,
doc='/',
version='1.0',
title=title,
description=desc,
security='Basic Auth',
authorizations=authorizations
)
# 如果是bearer验证
#authorizations = {
# 'Bearer Auth': {
# 'type': 'apiKey',
# 'in': 'header',
# 'name': 'Authorization'
# },
#}
#api = Api(app, security='Bearer Auth', authorizations=authorizations)
这样所有的request都将带上basic authorizations,如同curl命令curl --basic -u user:password http://www.example.com/posts/1
对于后端api应用程序endpoint来说,只需要将做base64解码即可
try:
encoded_auth_header = request.headers['Authorization'].split()[1]
username, password = b64decode(encoded_auth_header).split(':')
except Exception:
resp = app.response_class(
response=json.dumps({"error": "bad username/password"}),
status=401,
content_type='application/json'
)
return resp