Flask -Restplus + swagger,如何限制经过身份验证的用户+/角色

Dav*_*mic 5 flask flask-restplus

我有一个 Flask-Restplus 端点,如下所示:

@api.route('/apps/<uid>')
@api.doc(params={'uid': 'UUID of the app agent.'})
class AppAgentAPI(Resource):

    @login_required
    @api.marshal_with(app_agent)
    def get(self, uid):
          ...
Run Code Online (Sandbox Code Playgroud)

目前,此端点的 swagger 文档是公开的。

我想将对 swagger 文档的访问限制为仅经过身份验证的用户。(通过身份验证我的意思是关于我的 Flask 应用程序)。

如果我可以插入一些自定义逻辑以使其基于角色(即:只有我的应用程序中的管理员可以看到此端点的文档等),那就更好了。

我该怎么做呢?

Dav*_*mic 0

这是使用 @app.before_request 的 hack:

DOC_URL = api_bp.url_prefix + '/doc'

@app.before_request
def before_request():
    if request.path[0: len(DOC_URL)] == DOC_URL and not (current_user and current_user.is_authenticated):
        print("Unauthenticated user trying to access swagger docs. Redirecting")
        return redirect(url_for('user.login'))
Run Code Online (Sandbox Code Playgroud)

其中“api_bp”是 Swagger 正在记录的 Flask-restplus api 蓝图。

可以扩展它来检查用户角色。但是,这适用于整个文档页面,无法以这种方式实现更细粒度(逐个端点)规则。

Flask-restplus 原生的解决方案,即:直接使用 Flask-restplus API,具有更细粒度的规则,仍然是首选。