question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] How to authenticate static files?

See original GitHub issue

First 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:closed
  • Created 4 years ago
  • Reactions:7
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

24reactions
OscartGilescommented, Jul 8, 2021

Managed this after a poke around the Starlette source code. Seem to do the job. Checks you are authenticated and then delegates to StaticFiles

import typing
from pathlib import Path
import secrets

from fastapi import FastAPI, Request, HTTPException, status
from fastapi.staticfiles import StaticFiles
from fastapi.security import HTTPBasic, HTTPBasicCredentials


PathLike = typing.Union[str, "os.PathLike[str]"]
app = FastAPI()
security = HTTPBasic()


async def verify_username(request: Request) -> HTTPBasicCredentials:

    credentials = await security(request)

    correct_username = secrets.compare_digest(credentials.username, "user")
    correct_password = secrets.compare_digest(credentials.password, "password")
    if not (correct_username and correct_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect email or password",
            headers={"WWW-Authenticate": "Basic"},
        )
    return credentials.username


class AuthStaticFiles(StaticFiles):
    def __init__(self, *args, **kwargs) -> None:

        super().__init__(*args, **kwargs)

    async def __call__(self, scope, receive, send) -> None:

        assert scope["type"] == "http"

        request = Request(scope, receive)
        await verify_username(request)
        await super().__call__(scope, receive, send)


app.mount(
    "/static",
    AuthStaticFiles(directory=Path(__file__).parent / "static"),
    name="static",
)

0reactions
github-actions[bot]commented, Nov 22, 2022

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.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How do I serve static files with authentication? - Stack Overflow
How do I serve static files with authentication? · go to / · be redirected to facebook for login · go back to...
Read more >
App service to host static files with authentication
Hello,. I have set up a static web app to host our website files however I have a requirement to add authentication to...
Read more >
Best way to add authentication layer to static file requests?
If the static content is already on the web server, start simple. Skip (for now) the CGI script, proxy, URL rewriting, and caching....
Read more >
Are there any security risks associated with having static files ...
The static file middleware provides no authorization checks. Any files served by it, including those under wwwroot, are publicly available. See ...
Read more >
Protect Static Files In ASP.NET Web Forms With The Help Of ...
When a request comes, it will check whether it will be authenticated or not, if not it will redirect to login page otherwise...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found