django admin page and JWT

2019-04-23 05:14发布

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.

标签: django jwt
2条回答
三岁会撩人
2楼-- · 2019-04-23 05:55

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.

查看更多
小情绪 Triste *
3楼-- · 2019-04-23 05:59

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.

查看更多
登录 后发表回答