flask-openapi3 icon indicating copy to clipboard operation
flask-openapi3 copied to clipboard

Setting up auth for OpenAPI

Open Just-Drue opened this issue 11 months ago • 5 comments

Hi, a bit confused on what's the proper way to add auth to openapi endpoints?

Just-Drue avatar Dec 30 '24 14:12 Just-Drue

Here's an example of a project (flask-api-demo) for you to refer to:

  1. Define auth: https://github.com/luolingchun/flask-api-demo/blob/master/src/app/config.py#L51-L60
  2. Use auth: https://github.com/luolingchun/flask-api-demo/blob/master/src/app/api/user.py#L21

luolingchun avatar Jan 04 '25 02:01 luolingchun

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.

puittenbroek avatar May 06 '25 07:05 puittenbroek

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:

  1. JWT only
  2. API Key only
  3. 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 avatar Oct 17 '25 17:10 omikader

@omikader I have no experience with this, and there is usually only one type of validation for an endpoint.

luolingchun avatar Oct 18 '25 04:10 luolingchun

@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!

omikader avatar Oct 18 '25 20:10 omikader