fastapi-docshield 0.2.0__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. {fastapi_docshield-0.2.0 → fastapi_docshield-0.3.0}/.gitignore +7 -0
  2. fastapi_docshield-0.3.0/CHANGELOG.md +74 -0
  3. fastapi_docshield-0.3.0/PKG-INFO +265 -0
  4. fastapi_docshield-0.3.0/README.md +205 -0
  5. fastapi_docshield-0.3.0/fastapi_docshield/__init__.py +19 -0
  6. fastapi_docshield-0.3.0/fastapi_docshield/_templates.py +206 -0
  7. fastapi_docshield-0.3.0/fastapi_docshield/_version.py +3 -0
  8. fastapi_docshield-0.3.0/fastapi_docshield/docshield.py +659 -0
  9. fastapi_docshield-0.3.0/fastapi_docshield/py.typed +0 -0
  10. fastapi_docshield-0.3.0/fastapi_docshield/static_handler.py +123 -0
  11. {fastapi_docshield-0.2.0 → fastapi_docshield-0.3.0}/pyproject.toml +33 -14
  12. fastapi_docshield-0.3.0/tests/__init__.py +0 -0
  13. fastapi_docshield-0.3.0/tests/helpers.py +44 -0
  14. fastapi_docshield-0.3.0/tests/integration_app.py +15 -0
  15. fastapi_docshield-0.3.0/tests/test_auth.py +110 -0
  16. fastapi_docshield-0.3.0/tests/test_docshield.py +160 -0
  17. fastapi_docshield-0.3.0/tests/test_form_login.py +356 -0
  18. fastapi_docshield-0.3.0/tests/test_integration.py +111 -0
  19. fastapi_docshield-0.3.0/tests/test_pages.py +229 -0
  20. fastapi_docshield-0.3.0/tests/test_routes.py +98 -0
  21. fastapi_docshield-0.3.0/tests/test_user_tags.py +175 -0
  22. fastapi_docshield-0.2.0/PKG-INFO +0 -307
  23. fastapi_docshield-0.2.0/README.md +0 -249
  24. fastapi_docshield-0.2.0/fastapi_docshield/__init__.py +0 -18
  25. fastapi_docshield-0.2.0/fastapi_docshield/docshield.py +0 -425
  26. fastapi_docshield-0.2.0/fastapi_docshield/static_handler.py +0 -200
  27. {fastapi_docshield-0.2.0 → fastapi_docshield-0.3.0}/LICENSE +0 -0
  28. {fastapi_docshield-0.2.0 → fastapi_docshield-0.3.0}/fastapi_docshield/static/redoc/redoc.standalone.js +0 -0
  29. {fastapi_docshield-0.2.0 → fastapi_docshield-0.3.0}/fastapi_docshield/static/swagger/swagger-ui-bundle.js +0 -0
  30. {fastapi_docshield-0.2.0 → fastapi_docshield-0.3.0}/fastapi_docshield/static/swagger/swagger-ui.css +0 -0
@@ -71,3 +71,10 @@ dmypy.json
71
71
  # OS specific files
72
72
  .DS_Store
73
73
  **/.claude/settings.local.json
74
+
75
+ # Claude Code memory file
76
+ CLAUDE.md
77
+
78
+ # Tool caches and local lock file
79
+ .ruff_cache/
80
+ uv.lock
@@ -0,0 +1,74 @@
1
+ # Changelog
2
+
3
+ ## Version 0.3.0 (2026-11-24)
4
+
5
+ Everything that worked in 0.2.1 keeps working: the same arguments, the same URLs and the same default behavior.
6
+
7
+ ### Added
8
+
9
+ - **Form login** with `auth_method="form"`: a login page, a signed session cookie and a "Log out" link on the documentation pages (#4). HTTP Basic credentials are still accepted in this mode, so scripts keep working.
10
+ - **`user_tags`**: show each user only the routes, schemas and tag descriptions that match their tags (#5, #10, thanks @lokhandeganesh). Webhooks are filtered the same way.
11
+ - The app's Swagger UI settings are used: `swagger_ui_parameters` and `swagger_ui_init_oauth`.
12
+ - Apps behind a proxy with a root path work: the root path is put in front of the schema URL, the bundled files, the login redirects and the OpenAPI `servers` list.
13
+ - Python 3.8 and 3.9 are supported again, and the package is tested with FastAPI 0.68 up to the current release.
14
+ - Type information is shipped with the package (`py.typed`).
15
+
16
+ ### Fixed
17
+
18
+ - A user whose password or username has non-ASCII characters could never log in, and the attempt ended in a server error. Credentials are now read as UTF-8.
19
+ - Routes of the app that live under the docs path, like `/docs/guide`, were removed together with the default documentation routes. Now only the documentation routes themselves are removed.
20
+ - Swagger UI's OAuth2 redirect page (`/docs/oauth2-redirect`) was removed and never added back, which broke the "Authorize" flow for OAuth2. It works again.
21
+ - Custom CSS was loaded before the Swagger UI stylesheet in the default mode, so rules with the same weight lost. It now always comes last.
22
+ - An error in custom JavaScript replaced the whole page with "Failed to load documentation". The page now stays, and the error goes to the console.
23
+ - The app title is escaped in the pages.
24
+ - The ReDoc CDN URL pointed at `redoc@next`, which is a release candidate of ReDoc 3. It now points at `redoc@2`, the version FastAPI uses.
25
+ - A login attempt for a user that doesn't exist takes as long as one for a user that does.
26
+
27
+ ### Changed
28
+
29
+ - `requests` and `uvicorn` are no longer installed with the package, because it never used them. If your app imports them, add them to your own requirements.
30
+ - The documentation pages and the schema are sent with `Cache-Control: no-store`.
31
+ - The bundled Swagger UI and ReDoc files are served from memory, which also works on old FastAPI versions without `aiofiles`.
32
+
33
+ ### Removed
34
+
35
+ - `StaticHandler.get_fallback_html()`, which nothing used.
36
+ - The loose demo and manual test scripts in the repository root. The `examples` folder has a short example for each feature.
37
+
38
+ ## Version 0.2.1 (2025-08-17)
39
+
40
+ - **Fixed**: Blank page issue after authentication for some users
41
+ - Improved handling of custom URL parameters by storing them as instance variables
42
+ - Simplified `_setup_routes()` method for better maintainability
43
+ - Applied fix from PR #2 for more robust URL parameter handling
44
+ - **Fixed**: Route removal logic now correctly removes all default documentation routes
45
+ - Properly removes `/docs`, `/redoc`, and `/openapi.json` endpoints
46
+ - Prevents 500 errors when accessing old endpoints
47
+ - **Improved**: Example files and documentation
48
+ - Fixed `custom_styling.py` to work with uvicorn by adding default app variable
49
+ - Standardized credentials across all custom styling examples
50
+ - Added `python-multipart` to dev dependencies for form data handling
51
+ - Added clear run instructions in example files
52
+
53
+ ## Version 0.2.0 (2025-08-17)
54
+
55
+ - **Added**: Custom CSS and JavaScript injection support
56
+ - New `custom_css` parameter to inject custom styles into documentation pages
57
+ - New `custom_js` parameter to inject custom JavaScript for enhanced functionality
58
+ - Complete customization examples for dark theme, minimal theme, corporate branding, and analytics
59
+ - Support for both Swagger UI and ReDoc customization
60
+ - **Added**: Automatic CDN fallback to local files for better reliability
61
+ - Documentation now automatically falls back to bundled static files if CDN is unavailable
62
+ - New `prefer_local` option to always serve from local files
63
+ - New `use_cdn_fallback` option to control fallback behavior
64
+ - Bundled Swagger UI and ReDoc static files for offline capability
65
+ - **Fixed**: Static file URL bug that caused blank documentation pages
66
+ - Previously, when no custom CDN URLs were provided, the package would pass `None` values to FastAPI's documentation functions
67
+ - This resulted in HTML with `href="None"` and `src="None"`, causing white/blank pages
68
+ - Now properly handles default CDN URLs when custom URLs are not specified
69
+
70
+ ## Version 0.1.0 (2025-01-15)
71
+
72
+ - Initial release
73
+ - Basic HTTP authentication for FastAPI documentation endpoints
74
+ - Support for multiple users
@@ -0,0 +1,265 @@
1
+ Metadata-Version: 2.5
2
+ Name: fastapi-docshield
3
+ Version: 0.3.0
4
+ Summary: Protect FastAPI's /docs, /redoc and /openapi.json with HTTP Basic Auth or a login page
5
+ Project-URL: Homepage, https://github.com/georgekhananaev/fastapi-docshield
6
+ Project-URL: Bug Tracker, https://github.com/georgekhananaev/fastapi-docshield/issues
7
+ Project-URL: Documentation, https://github.com/georgekhananaev/fastapi-docshield#readme
8
+ Project-URL: Source Code, https://github.com/georgekhananaev/fastapi-docshield
9
+ Project-URL: Changelog, https://github.com/georgekhananaev/fastapi-docshield/blob/master/CHANGELOG.md
10
+ Author-email: George Khananaev <106206490+georgekhananaev@users.noreply.github.com>
11
+ License: MIT License
12
+
13
+ Copyright (c) 2025 George Khananaev
14
+
15
+ Permission is hereby granted, free of charge, to any person obtaining a copy
16
+ of this software and associated documentation files (the "Software"), to deal
17
+ in the Software without restriction, including without limitation the rights
18
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19
+ copies of the Software, and to permit persons to whom the Software is
20
+ furnished to do so, subject to the following conditions:
21
+
22
+ The above copyright notice and this permission notice shall be included in all
23
+ copies or substantial portions of the Software.
24
+
25
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31
+ SOFTWARE.
32
+ License-File: LICENSE
33
+ Keywords: authentication,documentation,fastapi,security
34
+ Classifier: Development Status :: 4 - Beta
35
+ Classifier: Framework :: FastAPI
36
+ Classifier: Intended Audience :: Developers
37
+ Classifier: License :: OSI Approved :: MIT License
38
+ Classifier: Operating System :: OS Independent
39
+ Classifier: Programming Language :: Python :: 3
40
+ Classifier: Programming Language :: Python :: 3.8
41
+ Classifier: Programming Language :: Python :: 3.9
42
+ Classifier: Programming Language :: Python :: 3.10
43
+ Classifier: Programming Language :: Python :: 3.11
44
+ Classifier: Programming Language :: Python :: 3.12
45
+ Classifier: Programming Language :: Python :: 3.13
46
+ Classifier: Programming Language :: Python :: 3.14
47
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
48
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
49
+ Classifier: Typing :: Typed
50
+ Requires-Python: >=3.8
51
+ Requires-Dist: fastapi>=0.68.0
52
+ Provides-Extra: dev
53
+ Requires-Dist: httpx>=0.23.0; extra == 'dev'
54
+ Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
55
+ Requires-Dist: pytest>=7.0.0; extra == 'dev'
56
+ Requires-Dist: requests>=2.28.0; extra == 'dev'
57
+ Requires-Dist: ruff>=0.6.0; extra == 'dev'
58
+ Requires-Dist: uvicorn>=0.18.0; extra == 'dev'
59
+ Description-Content-Type: text/markdown
60
+
61
+ # FastAPI DocShield
62
+
63
+ Protect FastAPI's `/docs`, `/redoc` and `/openapi.json` with a login: HTTP Basic Authentication or a login page.
64
+
65
+ [![PyPI version](https://img.shields.io/pypi/v/fastapi-docshield)](https://pypi.org/project/fastapi-docshield/)
66
+ [![Python versions](https://img.shields.io/pypi/pyversions/fastapi-docshield)](https://pypi.org/project/fastapi-docshield/)
67
+ [![Tests](https://github.com/georgekhananaev/fastapi-docshield/actions/workflows/python-tests.yml/badge.svg)](https://github.com/georgekhananaev/fastapi-docshield/actions/workflows/python-tests.yml)
68
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
69
+
70
+ ## Features
71
+
72
+ - Protects Swagger UI, ReDoc and the OpenAPI JSON with one call
73
+ - HTTP Basic Authentication, or a login page with a session and a "Log out" link
74
+ - Several users, and different documentation for different users
75
+ - Works without the CDN: Swagger UI and ReDoc are bundled as a fallback
76
+ - Custom CSS and JavaScript for the documentation pages
77
+ - Custom URLs for every endpoint, and support for apps behind a proxy
78
+ - No dependencies besides FastAPI
79
+
80
+ ## Installation
81
+
82
+ ```bash
83
+ pip install fastapi-docshield
84
+
85
+ # Or with uv
86
+ uv add fastapi-docshield
87
+ ```
88
+
89
+ ## Quick start
90
+
91
+ ```python
92
+ from fastapi import FastAPI
93
+ from fastapi_docshield import DocShield
94
+
95
+ app = FastAPI()
96
+
97
+
98
+ @app.get("/")
99
+ def read_root():
100
+ return {"Hello": "World"}
101
+
102
+
103
+ DocShield(
104
+ app=app,
105
+ credentials={
106
+ "admin": "admin_password",
107
+ "developer": "dev_password",
108
+ },
109
+ )
110
+ ```
111
+
112
+ Call `DocShield` after you create the app. `/docs`, `/redoc` and `/openapi.json` now ask for one of the usernames and passwords. In a real app, read the passwords from environment variables or your settings, not from the source code.
113
+
114
+ ## Login page with logout
115
+
116
+ HTTP Basic Authentication has no logout: the browser keeps sending the password until it is closed. If you want a login page and a "Log out" link, use form login:
117
+
118
+ ```python
119
+ DocShield(
120
+ app=app,
121
+ credentials={"admin": "admin_password"},
122
+ auth_method="form",
123
+ )
124
+ ```
125
+
126
+ A visitor who opens `/docs` is sent to a login page. After login the session lives in a signed, HTTP-only cookie for 8 hours (`session_max_age`, in seconds). The documentation pages get a "Log out" link in the bottom right corner; hide it with `custom_css=".docshield-logout { display: none; }"` if you link to the logout URL yourself.
127
+
128
+ Good to know:
129
+
130
+ - Scripts can still send HTTP Basic credentials, for example `curl -u admin:admin_password https://example.com/openapi.json`.
131
+ - The cookie is signed with a random secret that is made when the app starts. That is fine for a single process. If the app runs in several worker processes, or sessions should survive a restart, set `session_secret` to a long random value of your own, for example from an environment variable.
132
+ - A session ends when it expires, on logout, and when that user's password changes.
133
+ - The login page is at `/docshield/login` and logout at `/docshield/logout`. Change them with `login_url` and `logout_url`.
134
+
135
+ ## Different documentation for different users
136
+
137
+ `user_tags` maps a username to the route tags that user may see. A user with tags sees only the matching routes, their schemas and tag descriptions. Users that are missing from `user_tags`, or mapped to `None`, see everything.
138
+
139
+ ```python
140
+ @app.get("/", tags=["general"])
141
+ def read_root():
142
+ return {"Hello": "World"}
143
+
144
+
145
+ @app.post("/posts/{post_id}", tags=["admin"])
146
+ def create_post(post_id: int):
147
+ return {"id": post_id}
148
+
149
+
150
+ DocShield(
151
+ app=app,
152
+ credentials={
153
+ "admin": "admin_password",
154
+ "developer": "dev_password",
155
+ },
156
+ user_tags={
157
+ "admin": None, # Sees all routes and schemas
158
+ "developer": ["general"], # Sees only routes tagged "general"
159
+ },
160
+ )
161
+ ```
162
+
163
+ Routes without a tag are hidden from users that have a tag list.
164
+
165
+ This only changes what the documentation shows. It doesn't stop anyone from calling a hidden route, so the routes still need their own checks.
166
+
167
+ ## Working without the CDN
168
+
169
+ By default the pages load Swagger UI and ReDoc from the jsDelivr CDN and switch to the copies bundled in the package when the CDN can't be reached.
170
+
171
+ ```python
172
+ # Always use the bundled files, never the CDN
173
+ DocShield(app=app, credentials=credentials, prefer_local=True)
174
+
175
+ # CDN only, without the bundled fallback
176
+ DocShield(app=app, credentials=credentials, use_cdn_fallback=False)
177
+
178
+ # Your own copies
179
+ DocShield(
180
+ app=app,
181
+ credentials=credentials,
182
+ swagger_js_url="https://assets.example.com/swagger-ui-bundle.js",
183
+ swagger_css_url="https://assets.example.com/swagger-ui.css",
184
+ redoc_js_url="https://assets.example.com/redoc.standalone.js",
185
+ )
186
+ ```
187
+
188
+ ## Custom CSS and JavaScript
189
+
190
+ ```python
191
+ from pathlib import Path
192
+
193
+ DocShield(
194
+ app=app,
195
+ credentials={"admin": "admin_password"},
196
+ custom_css=Path("static/swagger_ui_dark.min.css").read_text(encoding="utf-8"),
197
+ custom_js="console.log('Documentation opened at', new Date().toISOString());",
198
+ )
199
+ ```
200
+
201
+ The CSS is added after the Swagger UI stylesheet, so your rules win. The JavaScript runs after the documentation has loaded; on the Swagger UI page the `ui` object is available to it.
202
+
203
+ A ready-made dark theme is in [fastapi-swagger-ui-dark-theme](https://github.com/georgekhananaev/fastapi-swagger-ui-dark-theme). See [examples/custom_styling.py](examples/custom_styling.py) for more themes: a minimal one, a corporate one with analytics, and a ReDoc one.
204
+
205
+ ## All options
206
+
207
+ | Option | Default | What it does |
208
+ | --- | --- | --- |
209
+ | `app` | required | The FastAPI app to protect |
210
+ | `credentials` | required | Dictionary of username to password |
211
+ | `docs_url` | `"/docs"` | Path of the Swagger UI page |
212
+ | `redoc_url` | `"/redoc"` | Path of the ReDoc page |
213
+ | `openapi_url` | `"/openapi.json"` | Path of the OpenAPI schema |
214
+ | `swagger_js_url`, `swagger_css_url`, `redoc_js_url` | `None` | Your own URLs for the Swagger UI and ReDoc files |
215
+ | `use_cdn_fallback` | `True` | Fall back to the bundled files when the CDN fails |
216
+ | `prefer_local` | `False` | Always use the bundled files |
217
+ | `custom_css`, `custom_js` | `None` | CSS and JavaScript to add to the documentation pages |
218
+ | `user_tags` | `None` | Username to allowed route tags |
219
+ | `auth_method` | `"basic"` | `"basic"` or `"form"` |
220
+ | `login_url`, `logout_url` | `"/docshield/login"`, `"/docshield/logout"` | Paths of the login page and the logout URL (form login) |
221
+ | `session_secret` | `None` | Secret for signing the session cookie; needed with several worker processes (form login) |
222
+ | `session_max_age` | `28800` | Lifetime of a session in seconds (form login) |
223
+
224
+ DocShield follows the app's own settings where they exist: a page that is switched off on the app (`FastAPI(docs_url=None)`) stays off, `swagger_ui_parameters` and `swagger_ui_init_oauth` are passed on to Swagger UI, and behind a proxy the root path is put in front of every URL.
225
+
226
+ ## Security notes
227
+
228
+ - Always serve the documentation over HTTPS. Both HTTP Basic credentials and the session cookie can be read on a plain HTTP connection.
229
+ - DocShield keeps casual visitors out of your documentation. It has no rate limiting or lockout, so use long random passwords.
230
+ - Passwords are compared in constant time, and the session cookie is signed with HMAC-SHA256.
231
+
232
+ ## Compatibility
233
+
234
+ - Python 3.8 to 3.14
235
+ - FastAPI 0.68 and newer
236
+
237
+ Every release is tested against the oldest and the newest supported versions.
238
+
239
+ ## Examples
240
+
241
+ ```bash
242
+ pip install uvicorn
243
+ uvicorn examples.basic_example:app --reload
244
+ ```
245
+
246
+ Then open http://localhost:8000/docs and log in with `admin` / `password123`. The [examples](examples) folder also has [form login](examples/form_login.py), [user tags](examples/user_tags.py) and [custom styling](examples/custom_styling.py).
247
+
248
+ ## Development
249
+
250
+ ```bash
251
+ git clone https://github.com/georgekhananaev/fastapi-docshield.git
252
+ cd fastapi-docshield
253
+ pip install -e ".[dev]"
254
+
255
+ pytest --cov=fastapi_docshield
256
+ ruff check . && ruff format --check .
257
+ ```
258
+
259
+ ## Changelog
260
+
261
+ See [CHANGELOG.md](CHANGELOG.md).
262
+
263
+ ## License
264
+
265
+ MIT License - Copyright (c) 2025 George Khananaev
@@ -0,0 +1,205 @@
1
+ # FastAPI DocShield
2
+
3
+ Protect FastAPI's `/docs`, `/redoc` and `/openapi.json` with a login: HTTP Basic Authentication or a login page.
4
+
5
+ [![PyPI version](https://img.shields.io/pypi/v/fastapi-docshield)](https://pypi.org/project/fastapi-docshield/)
6
+ [![Python versions](https://img.shields.io/pypi/pyversions/fastapi-docshield)](https://pypi.org/project/fastapi-docshield/)
7
+ [![Tests](https://github.com/georgekhananaev/fastapi-docshield/actions/workflows/python-tests.yml/badge.svg)](https://github.com/georgekhananaev/fastapi-docshield/actions/workflows/python-tests.yml)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
9
+
10
+ ## Features
11
+
12
+ - Protects Swagger UI, ReDoc and the OpenAPI JSON with one call
13
+ - HTTP Basic Authentication, or a login page with a session and a "Log out" link
14
+ - Several users, and different documentation for different users
15
+ - Works without the CDN: Swagger UI and ReDoc are bundled as a fallback
16
+ - Custom CSS and JavaScript for the documentation pages
17
+ - Custom URLs for every endpoint, and support for apps behind a proxy
18
+ - No dependencies besides FastAPI
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ pip install fastapi-docshield
24
+
25
+ # Or with uv
26
+ uv add fastapi-docshield
27
+ ```
28
+
29
+ ## Quick start
30
+
31
+ ```python
32
+ from fastapi import FastAPI
33
+ from fastapi_docshield import DocShield
34
+
35
+ app = FastAPI()
36
+
37
+
38
+ @app.get("/")
39
+ def read_root():
40
+ return {"Hello": "World"}
41
+
42
+
43
+ DocShield(
44
+ app=app,
45
+ credentials={
46
+ "admin": "admin_password",
47
+ "developer": "dev_password",
48
+ },
49
+ )
50
+ ```
51
+
52
+ Call `DocShield` after you create the app. `/docs`, `/redoc` and `/openapi.json` now ask for one of the usernames and passwords. In a real app, read the passwords from environment variables or your settings, not from the source code.
53
+
54
+ ## Login page with logout
55
+
56
+ HTTP Basic Authentication has no logout: the browser keeps sending the password until it is closed. If you want a login page and a "Log out" link, use form login:
57
+
58
+ ```python
59
+ DocShield(
60
+ app=app,
61
+ credentials={"admin": "admin_password"},
62
+ auth_method="form",
63
+ )
64
+ ```
65
+
66
+ A visitor who opens `/docs` is sent to a login page. After login the session lives in a signed, HTTP-only cookie for 8 hours (`session_max_age`, in seconds). The documentation pages get a "Log out" link in the bottom right corner; hide it with `custom_css=".docshield-logout { display: none; }"` if you link to the logout URL yourself.
67
+
68
+ Good to know:
69
+
70
+ - Scripts can still send HTTP Basic credentials, for example `curl -u admin:admin_password https://example.com/openapi.json`.
71
+ - The cookie is signed with a random secret that is made when the app starts. That is fine for a single process. If the app runs in several worker processes, or sessions should survive a restart, set `session_secret` to a long random value of your own, for example from an environment variable.
72
+ - A session ends when it expires, on logout, and when that user's password changes.
73
+ - The login page is at `/docshield/login` and logout at `/docshield/logout`. Change them with `login_url` and `logout_url`.
74
+
75
+ ## Different documentation for different users
76
+
77
+ `user_tags` maps a username to the route tags that user may see. A user with tags sees only the matching routes, their schemas and tag descriptions. Users that are missing from `user_tags`, or mapped to `None`, see everything.
78
+
79
+ ```python
80
+ @app.get("/", tags=["general"])
81
+ def read_root():
82
+ return {"Hello": "World"}
83
+
84
+
85
+ @app.post("/posts/{post_id}", tags=["admin"])
86
+ def create_post(post_id: int):
87
+ return {"id": post_id}
88
+
89
+
90
+ DocShield(
91
+ app=app,
92
+ credentials={
93
+ "admin": "admin_password",
94
+ "developer": "dev_password",
95
+ },
96
+ user_tags={
97
+ "admin": None, # Sees all routes and schemas
98
+ "developer": ["general"], # Sees only routes tagged "general"
99
+ },
100
+ )
101
+ ```
102
+
103
+ Routes without a tag are hidden from users that have a tag list.
104
+
105
+ This only changes what the documentation shows. It doesn't stop anyone from calling a hidden route, so the routes still need their own checks.
106
+
107
+ ## Working without the CDN
108
+
109
+ By default the pages load Swagger UI and ReDoc from the jsDelivr CDN and switch to the copies bundled in the package when the CDN can't be reached.
110
+
111
+ ```python
112
+ # Always use the bundled files, never the CDN
113
+ DocShield(app=app, credentials=credentials, prefer_local=True)
114
+
115
+ # CDN only, without the bundled fallback
116
+ DocShield(app=app, credentials=credentials, use_cdn_fallback=False)
117
+
118
+ # Your own copies
119
+ DocShield(
120
+ app=app,
121
+ credentials=credentials,
122
+ swagger_js_url="https://assets.example.com/swagger-ui-bundle.js",
123
+ swagger_css_url="https://assets.example.com/swagger-ui.css",
124
+ redoc_js_url="https://assets.example.com/redoc.standalone.js",
125
+ )
126
+ ```
127
+
128
+ ## Custom CSS and JavaScript
129
+
130
+ ```python
131
+ from pathlib import Path
132
+
133
+ DocShield(
134
+ app=app,
135
+ credentials={"admin": "admin_password"},
136
+ custom_css=Path("static/swagger_ui_dark.min.css").read_text(encoding="utf-8"),
137
+ custom_js="console.log('Documentation opened at', new Date().toISOString());",
138
+ )
139
+ ```
140
+
141
+ The CSS is added after the Swagger UI stylesheet, so your rules win. The JavaScript runs after the documentation has loaded; on the Swagger UI page the `ui` object is available to it.
142
+
143
+ A ready-made dark theme is in [fastapi-swagger-ui-dark-theme](https://github.com/georgekhananaev/fastapi-swagger-ui-dark-theme). See [examples/custom_styling.py](examples/custom_styling.py) for more themes: a minimal one, a corporate one with analytics, and a ReDoc one.
144
+
145
+ ## All options
146
+
147
+ | Option | Default | What it does |
148
+ | --- | --- | --- |
149
+ | `app` | required | The FastAPI app to protect |
150
+ | `credentials` | required | Dictionary of username to password |
151
+ | `docs_url` | `"/docs"` | Path of the Swagger UI page |
152
+ | `redoc_url` | `"/redoc"` | Path of the ReDoc page |
153
+ | `openapi_url` | `"/openapi.json"` | Path of the OpenAPI schema |
154
+ | `swagger_js_url`, `swagger_css_url`, `redoc_js_url` | `None` | Your own URLs for the Swagger UI and ReDoc files |
155
+ | `use_cdn_fallback` | `True` | Fall back to the bundled files when the CDN fails |
156
+ | `prefer_local` | `False` | Always use the bundled files |
157
+ | `custom_css`, `custom_js` | `None` | CSS and JavaScript to add to the documentation pages |
158
+ | `user_tags` | `None` | Username to allowed route tags |
159
+ | `auth_method` | `"basic"` | `"basic"` or `"form"` |
160
+ | `login_url`, `logout_url` | `"/docshield/login"`, `"/docshield/logout"` | Paths of the login page and the logout URL (form login) |
161
+ | `session_secret` | `None` | Secret for signing the session cookie; needed with several worker processes (form login) |
162
+ | `session_max_age` | `28800` | Lifetime of a session in seconds (form login) |
163
+
164
+ DocShield follows the app's own settings where they exist: a page that is switched off on the app (`FastAPI(docs_url=None)`) stays off, `swagger_ui_parameters` and `swagger_ui_init_oauth` are passed on to Swagger UI, and behind a proxy the root path is put in front of every URL.
165
+
166
+ ## Security notes
167
+
168
+ - Always serve the documentation over HTTPS. Both HTTP Basic credentials and the session cookie can be read on a plain HTTP connection.
169
+ - DocShield keeps casual visitors out of your documentation. It has no rate limiting or lockout, so use long random passwords.
170
+ - Passwords are compared in constant time, and the session cookie is signed with HMAC-SHA256.
171
+
172
+ ## Compatibility
173
+
174
+ - Python 3.8 to 3.14
175
+ - FastAPI 0.68 and newer
176
+
177
+ Every release is tested against the oldest and the newest supported versions.
178
+
179
+ ## Examples
180
+
181
+ ```bash
182
+ pip install uvicorn
183
+ uvicorn examples.basic_example:app --reload
184
+ ```
185
+
186
+ Then open http://localhost:8000/docs and log in with `admin` / `password123`. The [examples](examples) folder also has [form login](examples/form_login.py), [user tags](examples/user_tags.py) and [custom styling](examples/custom_styling.py).
187
+
188
+ ## Development
189
+
190
+ ```bash
191
+ git clone https://github.com/georgekhananaev/fastapi-docshield.git
192
+ cd fastapi-docshield
193
+ pip install -e ".[dev]"
194
+
195
+ pytest --cov=fastapi_docshield
196
+ ruff check . && ruff format --check .
197
+ ```
198
+
199
+ ## Changelog
200
+
201
+ See [CHANGELOG.md](CHANGELOG.md).
202
+
203
+ ## License
204
+
205
+ MIT License - Copyright (c) 2025 George Khananaev
@@ -0,0 +1,19 @@
1
+ """
2
+ FastAPI DocShield - protect FastAPI's documentation endpoints with a login.
3
+
4
+ The package secures FastAPI's built-in documentation endpoints
5
+ (/docs, /redoc and /openapi.json) with HTTP Basic Authentication
6
+ or with a login page.
7
+
8
+ Author: George Khananaev
9
+ License: MIT License
10
+ Copyright (c) 2025 George Khananaev
11
+ """
12
+
13
+ from ._version import __version__
14
+ from .docshield import DocShield
15
+
16
+ __author__ = "George Khananaev"
17
+ __license__ = "MIT"
18
+ __copyright__ = "Copyright (c) 2025 George Khananaev"
19
+ __all__ = ["DocShield", "__version__"]