[QUESTION] How to authenticate static files?
See original GitHub issueFirst check
- I used the GitHub search to find a similar issue and didn’t find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google “How to X in FastAPI” and didn’t find any information.
Description
How can I route /foo
to fe/private.html
for authorised users and fe/public.html
for everyone else, while ensuring that the <script src="fe/app.js"></script>
references inside those 2 HTML files are resolved?
I have already implemented Basic HTTP Authentication using fastapi.security.HTTPBasic
, and loading of static files using starlette.responses.HTMLResponse
.
Here is the snippet for loading the appropriate HTML file based on Basic HTTP Authentication username:
@app.get("/foo")
def get_private_content(username: str = Depends(get_current_username)):
with open('fe/private.html' if username == 'goodperson' else 'fe/public.html') as f:
return HTMLResponse(f.read())
Indeed, the above code loads the correct HTML file. But, even though the HTML file is correctly loaded, the fe/app.js
script reference inside the HTML file returns 404:
<script src="fe/app.js"></script>
I am aware that I can use app.mount
to expose the entire /fe
folder, as discussed in #130, but that would defeat the authentication because everyone can then access fe/private.html
directly.
In the context of fastapi, am I doing authentication of static files correctly?
Issue Analytics
- State:
- Created 4 years ago
- Reactions:7
- Comments:7 (2 by maintainers)
Top GitHub Comments
Managed this after a poke around the Starlette source code. Seem to do the job. Checks you are authenticated and then delegates to
StaticFiles
Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs.