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

define requestInterceptor to handle XSRF cookie to header inside Swagger UI

Open heeplr opened this issue 4 years ago • 4 comments

I'm using flask-security to generate session and csrf tokens. It set's a cookie and the web frontend is expected to copy that cookie to every model-changing request.

Swagger offers the requestInterceptor option to define a function that sets the header.

Is there a way to define a function in API_SPEC_OPTIONS or any other way, to achieve XSRF protection inside the Swagger UI?

heeplr avatar Jul 29 '21 10:07 heeplr

I can't look into this right now.

You may pass options with OPENAPI_SWAGGER_UI_CONFIG (see the docs: https://flask-smorest.readthedocs.io/en/latest/openapi.html). Would that be enough?

There's an old PR (#89 ) about auth issues that might be related (I'm just saying this because it is about auth, I didn't check any further). My point is/was to avoid putting too much HTML from doc display tools (swagger-ui and pals) into flask-smorest, but since those are stable, perhaps I could do it anyway. I don't even use Swagger-UI so I never needed that. We could check what is done in APIFlask.

lafrech avatar Jul 29 '21 20:07 lafrech

Thanks you. The problem seems to be that OPENAPI_SWAGGER_UI_CONFIG is json serialized and thus (obviously) can't contain javascript function objects. The PR is somewhat related as it embeds javscript which would allow some hackish solution. The only "clean" solution I could think of right now, would be some way to embed an unquoted string in the UI_CONFIG to define a function. Possibly by patching the json after serialization?

Maybe someone can come up with a good solution or you find the time at some point. For now, I turned off CSRF tokens completely in development mode and I guess that's what most people do which might be the reason this is rarely addressed.

heeplr avatar Jul 29 '21 20:07 heeplr

Didn't notice it was a function. Indeed, only json serializable options are supported with the simple mechanism I implemented.

I'd rather avoid adding a config parameter for each option of each UI, so a generic way would be nice. At least a way allowing users to achieve what they need in user code.

Meanwhile no CSRF in dev mode shouldn't be a blocker but I admit it is not ideal.

I'm afraid I won't be looking into this unless it becomes a blocker for our projects.

lafrech avatar Jul 29 '21 20:07 lafrech

I'll just leave that here for the future record. My first thought was some kind of JavaScript("...") wrapper that gets later embedded unquoted verbatim to be able to do something like

OPENAPI_SWAGGER_UI_CONFIG = {
    'requestInterceptor': JavaScript("(req) => { ... ; return my_req; }")
}

I'm not sure about a good way to implement that into flask-smorest, tho.

heeplr avatar Jul 29 '21 22:07 heeplr