django管理页面和JWT [英] django admin page and JWT

查看:122
本文介绍了django管理页面和JWT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在将django-rest-framework与django-rest-framework-jwt一起用于身份验证,除了在ip:port/admin/的django管理页面外,它都可在任何地方使用.那仍然需要用户名和密码.

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.

是否有设置或旁路方法可以识别JWT?

Is there a setting or way to bypass that so it recognizes the JWT?

使用名称/密码是否总是需要/admin/页?我认为内置的令牌身份验证可以使用它.

Is the /admin/ page always required to use name/password? I think the built in token auth works with it.

jwt是settings.py文件中设置的唯一身份验证.会话身份验证不再存在.

jwt is the only auth set in the settings.py file. Session authentication is not in there anymore.

推荐答案

问题是Django并不知道djangorestframework-jwt,而只有djangorestframework本身.对我有用的解决方案是创建一个简单的中间件,该中间件利用djangorestframework-jwt的auth

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

在settings.py中:

In settings.py:

MIDDLEWARE = [
    # others
    'myapp.middleware.jwt_auth_middleware',
]

然后在我的myapp/middleware.py

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

重要提示: 这是一种幼稚的方法,您不应在生产中运行,因此我仅启用此中间件if DEBUG.如果在生产环境中运行,则应该按照内置的django.contrib.auth模块的操作来缓存并懒惰地评估用户.

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.

这篇关于django管理页面和JWT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆