Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding Security Schemes #248

Open
yourbuddyconner opened this issue Jan 25, 2023 · 2 comments
Open

Adding Security Schemes #248

yourbuddyconner opened this issue Jan 25, 2023 · 2 comments

Comments

@yourbuddyconner
Copy link

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 for authorization middleware
  • flask-apispec for swagger docs

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:

  • The swagger 2.0 spec doesn't necessarily enforce this.
  • Not clear how to add security_scheme enforcement in the swagger UI docs

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
Copy link

freetsi commented Jan 5, 2024

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

@juandaospina
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants