6👍
The issue is that Django isn’t aware of djangorestframework-jwt, but only djangorestframework, itself. The solution that worked for me was to create a simple middleware that leveraged the auth of djangorestframework-jwt
In settings.py:
MIDDLEWARE = [
# others
'myapp.middleware.jwt_auth_middleware',
]
Then in my myapp/middleware.py
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from django.contrib.auth.models import AnonymousUser
from rest_framework import exceptions
def jwt_auth_middleware(get_response):
"""Sets the user object from a JWT header"""
def middleware(request):
try:
authenticated = JSONWebTokenAuthentication().authenticate(request)
if authenticated:
request.user = authenticated[0]
else:
request.user = AnonymousUser
except exceptions.AuthenticationFailed as err:
print(err)
request.user = AnonymousUser
response = get_response(request)
return response
return middleware
Important Note:
This is a naive approach that you shouldn’t run in production so I only enable this middleware if DEBUG
. If running in production, you should probably cache and lazily evaluate the user as done by the builtin django.contrib.auth
module.
-1👍
The problem can be not in the authentication method you use. If you customize User
model, it can happen that create_superuser
method doesn’t update is_active
flag in user instance details to True
. This case django authentication backend (if you use ModelBackend
) can recognize that user is not active and do not allow to authenticate. Simple check – just see what value has is_active
field of the superuser you create. If it False
, update it manually to True
, and try to login. If it is the reason of your problem you need to override create_superuser
and create_user
method of UserManager class.
- Background processing in Django without Celery
- Django days-of-week representation in model
- Django collectstatic no such file or directory
- How to I hide my secret_key using virtualenv and Django?
- Django override the form HTML label template?