Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding the schema for "unauthorized" to the OpenAPI #1189

Open
soerface opened this issue Jun 10, 2024 · 0 comments
Open

Adding the schema for "unauthorized" to the OpenAPI #1189

soerface opened this issue Jun 10, 2024 · 0 comments

Comments

@soerface
Copy link

soerface commented Jun 10, 2024

Take this example code from the documentation: https://django-ninja.dev/guides/authentication/#custom-exceptions

from ninja import NinjaAPI
from ninja.security import HttpBearer

api = NinjaAPI()

class InvalidToken(Exception):
    pass

@api.exception_handler(InvalidToken)
def on_invalid_token(request, exc):
    return api.create_response(request, {"detail": "Invalid token supplied"}, status=401)

class AuthBearer(HttpBearer):
    def authenticate(self, request, token):
        if token == "supersecret":
            return token
        raise InvalidToken


@api.get("/bearer", auth=AuthBearer())
def bearer(request):
    return {"token": request.auth}

This allows to add a custom authentication scheme, and return a custom response if the authentication failed.
However, the status code 401 and the form of the response is not documented in the API. If I try it out in the UI, it is also marked as "Undocumented":

image

I could document it myself by adding a schema, and adding it to the function decorator like this:

class BearerSchema(Schema):
    token: str


class UnauthorizedSchema(Schema):
    detail: str


@api.get(
    "/bearer",
    auth=AuthBearer(),
    response={
        200: BearerSchema,
        401: UnauthorizedSchema,
    },
)
def bearer(request):
    return {"token": request.auth}

However, I'm adding the auth handler globally, by doing api = NinjaAPI(auth=[AuthBearer()], ...), instead of adding it to every endpoint.

Therefore, I would also like to be able to add the UnauthorizedSchema globally as well. Is there a way to tie this scheme to the on_invalid_token exception handler or the custom AuthBearer class, so that every endpoint that requires authentication also contains the documentation about what is returned when the user isn't authenticated properly?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant