Search code examples
pythonflaskbasic-authenticationswagger-2.0connexion

How to specify the function used to validate the Basic auth with Flask-connexion and swagger-2.0 API


I'am using swagger 2.0 API with Flask-connexion.

In the swagger.yml file, I set the security definition to basic:

  BasicAuth:
    type: basic

And then, I added this security to the path I want to secure.

# Tenant paths
  /tenant:
    get:
      operationId: tenant.read_all
      tags:
        - Tenant
      summary: Read the entire set of tenants, sorted by name
      description: Read the entire set of tenants, sorted by name
      security:
        - basicAuth: []
      responses:
        200:
          description: Successfully read tenant set operation
          schema:
            type: array
            items:
              $ref: '#/definitions/Tenant'

But I don't understand how to specify the function which will validate the login, password. I need to collect these parameters and valide then before the path function get called.

If this implicitly defined using Flask-Login or Flask-BasicAuth for instance?

Or should it be done explicitly as without Flask-connexion by adding code in my tenant.py file such as:

@auth_basic.login_required
def read_all():
...

I would expect to have Flask-connexion redirect to an auth function which would validate the login and password, and then redirect to path method/function.


Solution

  • https://connexion.readthedocs.io/en/latest/security.html#basic-authentication

    You must define in your Swagger file:

    securityDefinitions: basic: type: basic x-basicInfoFunc: app.basic_auth

    The x-basicInfoFunc will map to the validation function , in this example the function basic_auth is in the app file.

    Complete example with Swagger: https://github.com/zalando/connexion/tree/master/examples/swagger2/basicauth

    Complete example with OpenApi: https://github.com/zalando/connexion/tree/master/examples/openapi3/basicauth