flask-restplus框架swagger页面的Authorizations认证登陆功能

效果

对于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
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值