jmcarp / flask-apispec

MIT License
653 stars 155 forks source link

Adding Security Schemes #248

Open yourbuddyconner opened 1 year ago

yourbuddyconner commented 1 year ago

Less of an issue, more of a resource for people looking to do this because the docs don't clearly specify it.

I am using a chain of flask plugins and it wasn't clear at which level to do it.

Using:

flask-httpauth implements a HTTPTokenAuth scheme, which based on my read of the code, enforces a Bearer prefix to an authorization header (as it should).

Problems:

Here's some code for how I was able to activate the authorization button in the swagger UI:

api_key_scheme = {"type": "apiKey", "scheme": "Bearer", "in": "header", "name": "Authorization", "description": "API Key"}
docs.spec.components.security_scheme("Bearer", api_key_scheme)
docs.spec.options["security"] = [{"Bearer": []}]

The apispec docs include mention of adding security schemes, but neglect to mention that you need to add a top-level reference to it in options if you want the UI to enforce auth, which I have added here.

Note: you must manually prefix your API token with Bearer like Bearer <token> in the swagger UI as I wasn't able to identify how to get it to do it automagically.

freetsi commented 8 months ago

Thank you very much I was searching for it the whole day!

juandaospina commented 3 months ago

docs.spec.options["security"] = [{"Bearer": []}] applies security to the entire specification, if you want to apply it individually it should be added to endpoints where needed with the @doc decorator, example:

@app.route("/protected")
    @doc(description="secure endpoint", security=[{"Bearer": []}])
    @jwt_required()
    def protected():
        pass