diff --git a/fastapi/staticfiles.py b/fastapi/staticfiles.py index 8e09fe9674..a54097e07b 100644 --- a/fastapi/staticfiles.py +++ b/fastapi/staticfiles.py @@ -94,22 +94,21 @@ class AuthStaticFiles(StaticFiles): self.on_error = on_error async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - if scope["type"] == "http": - request = Request(scope, receive) - try: - if self._auth_is_async: - await self.auth(request) - else: - await run_in_threadpool(self.auth, request) - except HTTPException as exc: - if self.on_error is not None: - response = await self.on_error(request, exc) - else: - response = PlainTextResponse( - str(exc.detail), - status_code=exc.status_code, - headers=getattr(exc, "headers", None), - ) - await response(scope, receive, send) - return + request = Request(scope, receive) + try: + if self._auth_is_async: + await self.auth(request) + else: + await run_in_threadpool(self.auth, request) + except HTTPException as exc: + if self.on_error is not None: + response = await self.on_error(request, exc) + else: + response = PlainTextResponse( + str(exc.detail), + status_code=exc.status_code, + headers=getattr(exc, "headers", None), + ) + await response(scope, receive, send) + return await super().__call__(scope, receive, send) diff --git a/tests/test_tutorial/test_static_files/test_tutorial002_auth.py b/tests/test_tutorial/test_static_files/test_tutorial002_auth.py new file mode 100644 index 0000000000..f400eead45 --- /dev/null +++ b/tests/test_tutorial/test_static_files/test_tutorial002_auth.py @@ -0,0 +1,37 @@ +import os +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +from tests.utils import workdir_lock + + +@pytest.fixture(scope="module") +def client(): + private_dir: Path = Path(os.getcwd()) / "private_files" + private_dir.mkdir(exist_ok=True) + sample_file = private_dir / "secret.txt" + sample_file.write_text("This is a private file.") + from docs_src.static_files.tutorial002_auth_py310 import app + + with TestClient(app) as client: + yield client + sample_file.unlink() + private_dir.rmdir() + + +@workdir_lock +def test_without_auth(client: TestClient): + response = client.get("/private/secret.txt") + assert response.status_code == 401, response.text + + +@workdir_lock +def test_with_valid_auth(client: TestClient): + response = client.get( + "/private/secret.txt", + headers={"Authorization": "Bearer mysecrettoken"}, + ) + assert response.status_code == 200, response.text + assert response.text == "This is a private file."