OpenAPITools / OpenAPITools/openapi-generator

[REQ] [python-fastapi] Support optional authentication

Open
#20,049 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Enhancement: Feature
Dominant language
Java
Stars
26.8k
Forks
7.7k
PR merge metrics
PR metrics pending

Description

Is your feature request related to a problem? Please describe.

OAS lets you declare a service with optional authentication, for example: https://gist.github.com/micolous/2593789b5b797015dc32ddf049a028a1#file-optional_auth_openapi-yaml-L69-L72

With the Python-FastAPI generator (v7.9.0) this results in:

# security_api.py
oauth2_code = OAuth2AuthorizationCodeBearer(
    authorizationUrl="https://auth.example.com/authorize",
    tokenUrl="https://auth.example.com/token",
    refreshUrl="",
    scopes={
        "read:api": "API read access",
        "special:api": "API special access",
        "write:api": "API write access",
    }
)

def get_token_oauth(
    security_scopes: SecurityScopes, token: str = Depends(oauth2_code)
) -> TokenModel:
    ...

# apis/default_api.py
@router.get(
    "/default_optional_auth",
    responses={
        200: {"model": str, "description": "Information about the currently logged in user."},
    },
    tags=["default"],
    summary="Method with optional authentication, from a default policy.",
    response_model_by_alias=True,
)
async def default_optional_auth(
    token_oauth: TokenModel = Security(
        get_token_oauth, scopes=["read:api"]
    ),
) -> str:
    if not BaseDefaultApi.subclasses:
        raise HTTPException(status_code=500, detail="Not implemented")
    return await BaseDefaultApi.subclasses[0]().default_optional_auth()

FastAPI's OAuth2 flows (like OAuth2AuthorizationCodeBearer) default to auto_error=True, which causes them to reject any requests which do not include authentication.

Describe the solution you'd like

With the service definition provided, there should be multiple OAuth2AuthorizationCodeBearer instances:

  • default_optional_auth and path_level_optional_auth should have an instance with auto_error=False
  • required_auth should have an instance with auto_error=True

The API implementations (in apis/default_api.py should declare token_oauth: Optional[TokenModel] = Security(... for default_optional_auth and path_level_optional_auth.

This will also need to end up in the base APIs, once #20048 is fixed.

Describe alternatives you've considered

Additional context

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Python-FastAPI generator paths that produce security_api.py and apis/default_api.py, using the optional_auth_openapi.yaml service definition from the issue as the reproduction input. Compare generated handling for default_optional_auth, path_level_optional_auth, and required_auth, including the referenced base APIs and #20048 dependency. Done means optional operations allow unauthenticated requests while required_auth still enforces authentication, with matching Optional[TokenModel] declarations.

Written by the indexing model from the issue text.

Assessment

Tech stack
fastapi, openapi, python
Domain
api, tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.