Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Añadir contraseña a Swagger en FastAPI

Tiempo de lectura: 2 minutos

Hoy vamos a aprender cómo podemos añadir una contraseña de acceso a Swagger en FastAPI. De esta forma securizaremos en dashboard de Swagger y el json de definiciones.

Cascada impresionante - Pexels

Lo primero que haremos es ir al main.py de FastAPI.

Vamos a crear un Middleware que nos permitirá interceptar las llamadas al endpoint /openapi.json y /docs y solicitaremos un usuario y contraseña en esos endpoints.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import os
from dotenv import load_dotenv
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
import base64
load_dotenv()
# Configuración de la autenticación básica
security = HTTPBasic()
valid_username = os.getenv("SWAGGER_USER")
valid_password = os.getenv("SWAGGER_PASSWORD")
def authenticate(credentials: HTTPBasicCredentials = Depends()):
if credentials.username != valid_username or credentials.password != valid_password:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)
# Middleware para autenticar las rutas de documentación
class AuthDocsMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
# Verificamos si es una solicitud a /docs o /openapi.json (y cualquier otra ruta que contenga "openapi.json")
if "/openapi.json" in request.url.path or "/docs" in request.url.path:
auth_header = request.headers.get("Authorization")
if not auth_header or not auth_header.startswith("Basic "):
# Si no hay encabezado Authorization, respondemos con 401 y el encabezado WWW-Authenticate
return JSONResponse(
status_code=status.HTTP_401_UNAUTHORIZED,
content={"detail": "Missing or invalid authorization header"},
headers={"WWW-Authenticate": "Basic"},
)
# Extraemos y decodificamos las credenciales
try:
base64_credentials = auth_header[6:] # Eliminamos el prefijo "Basic "
decoded_credentials = base64.b64decode(base64_credentials).decode("utf-8")
username, password = decoded_credentials.split(":", 1)
# Creamos el objeto de credenciales
credentials = HTTPBasicCredentials(username=username, password=password)
# Ejecutamos la función de autenticación
authenticate(credentials)
except Exception as e:
return JSONResponse(
status_code=status.HTTP_401_UNAUTHORIZED,
content={"detail": "Incorrect username or password"},
headers={"WWW-Authenticate": "Basic"},
)
return await call_next(request)
# Agregamos el middleware
app.add_middleware(AuthDocsMiddleware)
import os from dotenv import load_dotenv from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import HTTPBasic, HTTPBasicCredentials from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from starlette.middleware.base import BaseHTTPMiddleware import base64 load_dotenv() # Configuración de la autenticación básica security = HTTPBasic() valid_username = os.getenv("SWAGGER_USER") valid_password = os.getenv("SWAGGER_PASSWORD") def authenticate(credentials: HTTPBasicCredentials = Depends()): if credentials.username != valid_username or credentials.password != valid_password: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", headers={"WWW-Authenticate": "Basic"}, ) # Middleware para autenticar las rutas de documentación class AuthDocsMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): # Verificamos si es una solicitud a /docs o /openapi.json (y cualquier otra ruta que contenga "openapi.json") if "/openapi.json" in request.url.path or "/docs" in request.url.path: auth_header = request.headers.get("Authorization") if not auth_header or not auth_header.startswith("Basic "): # Si no hay encabezado Authorization, respondemos con 401 y el encabezado WWW-Authenticate return JSONResponse( status_code=status.HTTP_401_UNAUTHORIZED, content={"detail": "Missing or invalid authorization header"}, headers={"WWW-Authenticate": "Basic"}, ) # Extraemos y decodificamos las credenciales try: base64_credentials = auth_header[6:] # Eliminamos el prefijo "Basic " decoded_credentials = base64.b64decode(base64_credentials).decode("utf-8") username, password = decoded_credentials.split(":", 1) # Creamos el objeto de credenciales credentials = HTTPBasicCredentials(username=username, password=password) # Ejecutamos la función de autenticación authenticate(credentials) except Exception as e: return JSONResponse( status_code=status.HTTP_401_UNAUTHORIZED, content={"detail": "Incorrect username or password"}, headers={"WWW-Authenticate": "Basic"}, ) return await call_next(request) # Agregamos el middleware app.add_middleware(AuthDocsMiddleware)
import os
from dotenv import load_dotenv
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
import base64

load_dotenv()


# Configuración de la autenticación básica
security = HTTPBasic()
valid_username = os.getenv("SWAGGER_USER")
valid_password = os.getenv("SWAGGER_PASSWORD")

def authenticate(credentials: HTTPBasicCredentials = Depends()):
    if credentials.username != valid_username or credentials.password != valid_password:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Basic"},
        )


# Middleware para autenticar las rutas de documentación
class AuthDocsMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        # Verificamos si es una solicitud a /docs o /openapi.json (y cualquier otra ruta que contenga "openapi.json")
        if "/openapi.json" in request.url.path or "/docs" in request.url.path:
            auth_header = request.headers.get("Authorization")
            if not auth_header or not auth_header.startswith("Basic "):
                # Si no hay encabezado Authorization, respondemos con 401 y el encabezado WWW-Authenticate
                return JSONResponse(
                    status_code=status.HTTP_401_UNAUTHORIZED,
                    content={"detail": "Missing or invalid authorization header"},
                    headers={"WWW-Authenticate": "Basic"},
                )

            # Extraemos y decodificamos las credenciales
            try:
                base64_credentials = auth_header[6:]  # Eliminamos el prefijo "Basic "
                decoded_credentials = base64.b64decode(base64_credentials).decode("utf-8")
                username, password = decoded_credentials.split(":", 1)

                # Creamos el objeto de credenciales
                credentials = HTTPBasicCredentials(username=username, password=password)

                # Ejecutamos la función de autenticación
                authenticate(credentials)

            except Exception as e:
                return JSONResponse(
                    status_code=status.HTTP_401_UNAUTHORIZED,
                    content={"detail": "Incorrect username or password"},
                    headers={"WWW-Authenticate": "Basic"},
                )

        return await call_next(request)


# Agregamos el middleware
app.add_middleware(AuthDocsMiddleware)

Ahora crearemos un archivo .env con los credenciales necesarios:

.env

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
SWAGGER_USER="admin"
SWAGGER_PASS="admin123"
SWAGGER_USER="admin" SWAGGER_PASS="admin123"
SWAGGER_USER="admin"
SWAGGER_PASS="admin123"

Y cuándo accedamos al Swagger /docs nos pedirá autenticación:

Solicitando acceso por contraseña al Swagger
0

Deja un comentario