Fastapi: [QUESTION] Authentication for StreamingResponse

Created on 16 Sep 2019  路  4Comments  路  Source: tiangolo/fastapi

Description

I followed the excellent guide to implement oauth authentication (with JWT) from the docs.

However, when I'm linking directly to files in the browser (files are returned with starlette.responses.StreamingResponse), it is not possible to set the headers and the Bearer token.

Is it possible to authenticate in some other way, for example by using query string parameters or short lived temporary tokens?

Additional context
My workaround is to handle it in the front end as described in this Stack Overflow post https://stackoverflow.com/a/43133108

question

All 4 comments

In general, you should avoid relying solely on query parameters for authentication as urls may not be well secured (e.g., could show up in link history in a shared browser).

Depending on your security requirements, if you don't want to make use of a front-end trick like the one you linked, you could

  1. Create a short-term link with an expiration (this should be possible using pyjwt or itsdangerous) -- the signed claims could be passed as a query or path parameter
  2. Optionally, restrict the link to a single (or small number) of uses, if you also control the file sharing.

Separately, I'm not very knowledgeable about browsers, but might it be possible to use a cookie for this use case? If a set cookie can be read from the browser even when just a link is clicked, then you should be able to use your usual token-based auth without a problem -- just pass it via cookie rather than via authorization header.

You could use a shorter-term temporary and/or one-time-use token in the cookie if there are security concerns with using cookies (again, I'm not an expert).

Thank you for your answer.
I will investigate the proposed solutions and see what will work.

As @dmontagu says, a short-lived URL would work. That would be especially useful if you want users to be able to share the link for someone else to download the file with a short expiration.

On the other side, yep, you could set a cookie with the token in the same response with the token in JSON (during login).

Then you would create a dependency that checks for a bearer token OR a cookie.

Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zero0nee picture zero0nee  路  3Comments

RogerioDosSantos picture RogerioDosSantos  路  3Comments

danielgtaylor picture danielgtaylor  路  3Comments

kkinder picture kkinder  路  3Comments

updatatoday picture updatatoday  路  3Comments