I implemented my endpoints documentation behind authentication using basic auth, based on @EasonC13 in the link, only using two other functions to query my database and other one to compare password tokens.
https://github.com/tiangolo/fastapi/discussions/8169
When everything goes fine and i get the answer from the endpoint, it doesn't give me the documentation for my endpoints, instead it gives documentation for the new 2 endpoints for the documentation authentication.
Here is the code:
Main code file:
from fastapi import FastAPI
from routers import cliente, produto, faturaVenda, autoDocumentation
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
app.include_router(cliente.router)
app.include_router(produto.router)
app.include_router(faturaVenda.router)
app.include_router(autoDocumentation.router)
@app.get("/test", tags=["Hello World"])
def hello_world() -> None:
return {"Hello my first FastAPI api"}
The endpoints for the documentation based on authentication:
import sys
sys.path.insert(1, "/Users/user/Desktop/Api")
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from authentication.autoDocumentationAuthentication import check_entity_credencials
from fastapi import Depends, APIRouter
router = APIRouter()
@router.get("/docs")
async def get_documentation(username: str = Depends(check_entity_credencials)):
return get_swagger_ui_html(openapi_url="/openapi.json", title="docs")
@router.get("/openapi.json")
async def openapi(username: str = Depends(check_entity_credencials)):
return get_openapi(title = "FastAPI", version="0.1.0", routes=router.routes)
The function check_entity_credencials is where the basic auth logic is stored, here's it:
import sys
sys.path.insert(1, "/Users/user/Desktop/project/Api")
from fastapi.security import HTTPBasicCredentials, HTTPBasic
from fastapi import Depends, HTTPException, status
from repository.configuration.databaseConfigurationAndQuery import DatabaseConnectorAndQuery
from utils.hasher import hashString, verifyHash
security = HTTPBasic()
def check_entity_credencials(credentials: HTTPBasicCredentials = Depends(security)):
correctEntityId = check_entity_id_in_db(credentials.username)
correct_password = check_entity_password_in_db(correctEntityId)
if correctEntityId != None and correct_password != None:
if verifyHash(credentials.password, correct_password):
return credentials.username
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Password or ID passed is incorrect",
headers={"WWW-Authenticate": "Basic"},
)
Before implementing the documentation behing authentication, the '/doc' would return:
- endpoint 1
- endpoint 2
- endpoint 3
- ...
Then after implementing the authentication:
- getdocumentation
- openapi
Any hints on a way to return auto documentation page with my actuall api's like the one it was returning as default?