Setting up auth for OpenAPI
Hi, a bit confused on what's the proper way to add auth to openapi endpoints?
Here's an example of a project (flask-api-demo) for you to refer to:
- Define auth: https://github.com/luolingchun/flask-api-demo/blob/master/src/app/config.py#L51-L60
- Use auth: https://github.com/luolingchun/flask-api-demo/blob/master/src/app/api/user.py#L21
That is the documentation part. Authentication is usually done via decorators. One of the issues this project has, is that is causes the incoming payload to be validated before any decorators (auth..) being applied.
That is quite a dangerous approach. You want to be able to do auth first.
Hello @luolingchun, thanks for this project and the wonderful example using authentication. I was wondering if you had any thoughts on the best way to write an endpoint that supported multiple forms of authentication -- say JWT and API Key.
In my application, we have three kinds of endpoints:
- JWT only
- API Key only
- Both JWT and API Key
@api.get("entities/<int:entity_id>", security=JWT + KEY)
@auth_required()
def get_entity(path: EntityPath):
return jsonify(...)
In my auth_required decorator, I was wondering if it would be possible to know which values have been set for security so it can dynamically know which security strategies to evaluate.
For example, if security= JWT + KEY or abp_securtiy = JWT + KEY then I know my auth_required decorator should check both the Authorization and X-APP-API-KEY headers before rejecting the request.
If only JWT is supported, then it shouldn't even try checking the X-APP-API-KEY.
Let me know if this request makes sense.
@omikader I have no experience with this, and there is usually only one type of validation for an endpoint.
@luolingchun thanks for the quick response.
Does the flask-openapi3 package attach any openapi metadata on the route handler?
That way I can reliably derive the supported security schemes per endpoint in my auth decorator and write the conditional logic.
No worries, if not.
Thanks again!