Skip to content

[BUG] Authentication runs very late after view decorators #1646

@apapsch

Description

@apapsch

Describe the bug

Authentication runs very late after view decorators. Take this example:

# main router:
api = NinjaAPI(auth=BearerAuth())
api.add_decorator(activate_tenant, mode="view")

# app-specific endpoint in another file:

@router.post("/report")
@decorate_view(save_request)
async def hello(request, report: Report): ...
  • save_request is a decorator with the characteristics:
    • must run before validation of the request (to save possibly malformed requests because of client deficiencies)
    • relies on activate_tenant to set some context variable used for the database router.
  • activate_tenant on the other hand relies on request.auth being set by the auth handler.
  • activate_tenant fails because request.auth is not set, as it runs before the auth handler.

I guess I can work around the issue by not using NinjaAPI auth parameter, instead rolling my own authentication as a view decorator.

However, I would have expected that authentication happens as early as possible in the request flow, before any decorators, to keep the code path short for unauthenticated clients (and of course allow my scenario described above).

Versions (please complete the following information):

  • Python version: 3.14
  • Django version: 5.2
  • Django-Ninja version: 1.5.2
  • Pydantic version: 2.12.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions