vitalik/django-ninja

[BUG] JWTAuth() is inconsistent with django authentication?

Opened this issue · 1 comments

@api.get(
    path="/hello-user", 
    response=UserSchema, 
    auth=[JWTAuth()]
)
def hello_user(request):
    return request.user

>>> 
"GET - hello_user /api/hello-user" 
Unauthorized: /api/hello-user

When disabling auth

@api.get(
    path="/hello-user", 
    response=UserSchema, 
    # auth=[JWTAuth()]
)
def hello_user(request):
    return request.user

>>>
"GET - hello_user /api/hello-user" 
[02/Sep/2024 16:50:14] "GET /api/hello-user HTTP/1.1" 200 113
{"username": "neldivad", "is_authenticated": true, "email": "neldivad@gmail.com"}
# ??? Django says I'm authenticated by Ninja disagrees ???

This decorator is so frustrating to use. Different apps gets authenticated and sometimes it doesn't.

I tried logging out and logging in from admin page. Tried different browser, Tried incognito. This JWT auth is the one that has been giving me a huge issue.

Django Ninja's auth will store the authenticated entity in request.auth. request.user is still what authenticated by your Django settings, e.g. user of current session with django.contrib.sessions.middleware.SessionMiddleware.

Example from doc:

from ninja import NinjaAPI
from ninja.security import django_auth

api = NinjaAPI(csrf=True)


@api.get("/pets", auth=django_auth)
def pets(request):
    return f"Authenticated user {request.auth}"