0

My fastAPI application has middleware implemented and checks for an OIDC token before continuting. This all works fine when the API is directly called for example through postman and an authorization header is passed in with the token.

I wanted to be able to test my API's through the swagger "/docs" page as well. I found some information about getting a popup on the top right of swagger to enter in a token and be able to use it in the headers. However this token seems to not bee passed in to my other API's.

import logging
import os
import traceback
from datetime import datetime
import uvicorn
from fastapi import FastAPI, Depends, Security, Request
from fastapi.middleware.cors import CORSMiddleware
from auth import AuthHeaderMiddleware, OidcAuthenticationMiddleware
from elasticapm.contrib.starlette import make_apm_client, ElasticAPM
from starlette.requests import Request
from starlette.responses import Response
from fastapi.security import HTTPBearer
from fastapi.security.api_key import APIKeyHeader


from routes import (
    component_route,
)

app = FastAPI()

security = HTTPBearer()


@app.get("/")
def main(authorization: str = Depends(security)):
    return authorization.credentials


app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.add_middleware(OidcAuthenticationMiddleware)
app.include_router(component_route.component_router, tags=["Components"])

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=3000, debug=True)

Component route below

from typing import List, Any, Optional
from fastapi import APIRouter, Header
from controller.component_controller import (
    get_components,
)
from models.component_model import ComponentOut, ComponentIn, ComponentHistoryOut, ComponentHeaderOut

component_router = APIRouter()


@component_router.get(
    "/api/get_component_header",
    response_model=List[ComponentHeaderOut],
    response_model_exclude_unset=True,
    response_model_by_alias=False,
)
async def GetComponentHeader(
    limit: Optional[int] = None,
    offset: Optional[int] = None,
    x_vendor_numbers: Optional[Any] = Header(None),
    x_internaluser: Optional[bool] = Header(None),
):
    data = await get_components(vendor_number=x_vendor_numbers, limit=limit, offset=offset)
    return data

When in debugging mode I can see when I access the "/" endpoint the request object has a header key of authorization with the correct value. However if I go to any of my other API's like the component route. When I send a request via swagger these API's do not have any header key/value of authorization.

Is there a way to initialize the token just once via the HTTPBearer() method and have that header be used in all my other endpoints without manually having to add it to every single one?

My code currently works fine via postman and direct API access however I would like to be able to access and use API's via swagger without causing any issues.

Masterstack8080
  • 185
  • 1
  • 3
  • 11
  • You might find [this](https://stackoverflow.com/a/74088523/17865804) and [this](https://stackoverflow.com/a/74268404/17865804) helpful. – Chris Jul 01 '23 at 09:36

0 Answers0