5

I have a Flask-Restplus endpoint like so:

@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):
          ...

Currently the swagger docs for this endpoint are public.

I'd like to restrict access to swagger docs to authenticated users only. (By authenticated I mean with respect to my Flask app).

Even better if I can insert some custom logic to make it role-based (ie: only admins within my app can see the docs to this endpoint, etc).

How do I do this?

David Simic
  • 2,061
  • 2
  • 19
  • 33

1 Answers1

0

This is a hack using @app.before_request:

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'))

Where "api_bp" is the flask-restplus api blueprint which is being documented by Swagger.

It could be extended to check the user roles. However, this applies to the entire doc page, finer grained (endpoint by endpoint) rules can't be implemented in this way.

A solution native to flask-restplus, ie: directly using the flask-restplus API, with finer grained rules, would still be preferred.

David Simic
  • 2,061
  • 2
  • 19
  • 33