vitalik / django-ninja

💨 Fast, Async-ready, Openapi, type hints based framework for building APIs
https://django-ninja.dev
MIT License
7.05k stars 422 forks source link

[BUG] Combining JWTAuth with django_auth only works in that order #1125

Open bastiaan85 opened 5 months ago

bastiaan85 commented 5 months ago

Describe the bug When combining JWTAuth from django-jwt-auth with django_auth, if the latter precedes the former in the auth=[] parameter, calls using Bearer auth fail on "detail: CSRF check Failed". When inverting the order, both work.

    api = NinjaExtraAPI(
    title="My API",
    csrf=False,
    docs=Swagger(),
    docs_decorator=login_required,
    docs_url="/swagger",
    auth=[JWTAuth(), django_auth],  # working
    renderer=ORJSONRenderer(),
    urls_namespace="api",
)

while auth= [django_auth,JWTAuth()] generates the csrf error.

Versions (please complete the following information):

AndrewGrossman commented 3 months ago

+1. I also encountered this, Python 3.12.2, Django 5.0.6, Django-Ninja 1.1.0.

import logging

from django.conf import settings
from ninja.security import HttpBearer
from ninja.security import django_auth_superuser

class AuthBearer(HttpBearer):
    def authenticate(self, request, token):
        if token in settings.ALLOWED_API_BEARER_TOKENS:
            return token

        if not settings.IS_DEPLOYED:
            logging.info("Bypassing bearer token check for non-deployed environment")
            return "not-deployed"

        return None

default_auth = [django_auth_superuser, AuthBearer()]

The above auth defined on my API gives CSRF issues, even if the target endpoint is marked as csrf_exempt. Flipping the auth order as @bastiaan85 did seems to solve the issue for me.