We are using django-rest-framework with django-rest-framework-jwt for authentication and it works everywhere except the django admin page at ip:port/admin/
. That still wants username and password.
Is there a setting or way to bypass that so it recognizes the JWT?
Is the /admin/
page always required to use name/password? I think the built in token auth works with it.
jwt is the only auth set in the settings.py file. Session authentication is not in there anymore.
Login Logout API Authentication using Django Rest Framework We have already create a app with name accounts. Inside this app we will create our LoginView. Note – login(request, user) line in above code, will also create session based authentication with token based authentication. That's it.
JWT authentication is used for token authentication and it is really a popular method for authentication in Django. JWT stand for JSON Web Token. Let's see how to work with it. First, install a package − pip install djangorestframework-simplejwt pip install djangorestframework.
Authentication backends provide an extensible system for when a username and password stored with the user model need to be authenticated against a different service than Django's default. You can give your models custom permissions that can be checked through Django's authorization system.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With