vitalik / django-ninja

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

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

Open neldivad opened 2 months ago

neldivad commented 2 months ago
@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.

Xdynix commented 1 month ago

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}"