gpt4 book ai didi

python - 如何添加身份验证中间件 JWT django?

转载 作者:行者123 更新时间:2023-12-03 23:18:05 25 4
gpt4 key购买 nike

我正在尝试创建一个中间件来使用 JWT 进行身份验证,但在 View 中 request.user 始终是 AnonymUser。

当我验证中间件通过用户模型更改 request.user 时,确实如此,但是在到达 View 时,由于某种原因 request.user 始终是 anonymousUser

我正在使用 Django 1.11

# coding=utf-8
from django.utils.functional import SimpleLazyObject
from django.utils.deprecation import MiddlewareMixin
from django.contrib.auth.models import AnonymousUser, User
from django.conf import settings
from django.contrib.auth.middleware import get_user
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
import jwt
import json


class JWTAuthenticationMiddleware(MiddlewareMixin):
def process_request(self, request):
request.user = SimpleLazyObject(lambda: self.__class__.get_jwt_user(request))

@staticmethod
def get_jwt_user(request):
user_jwt = get_user(request)
if user_jwt.is_authenticated():
return user_jwt
token = request.META.get('HTTP_AUTHORIZATION', None)
user_jwt = None
if token is not None:
try:
user_jwt = jwt.decode(
token,
settings.SECRET_KEY,
algorithms=['HS256']
)
user_jwt = User.objects.get(
id=user_jwt['user_id']
)
except Exception as e:
user_jwt = AnonymousUser
return user_jwt





MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'user.middlewares.JWTAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

最佳答案

我试图复制您的错误,但就我而言,它运行良好,我认为您的问题的根本原因是异常处理方法。 jwt.decode 可以引发多种类型的异常,包括 DecodeError , ExpiredSignatureError , InvalidKeyError还有更多,即使是从 jwt.decode 检索到的 dict 也没有“user_id”键。

这是一个完整的工作代码

# coding=utf-8
import jwt
import traceback

from django.utils.functional import SimpleLazyObject
from django.utils.deprecation import MiddlewareMixin
from django.contrib.auth.models import AnonymousUser, User
from django.conf import LazySettings
from django.contrib.auth.middleware import get_user

settings = LazySettings()


class JWTAuthenticationMiddleware(MiddlewareMixin):
def process_request(self, request):
request.user = SimpleLazyObject(lambda: self.__class__.get_jwt_user(request))

@staticmethod
def get_jwt_user(request):

user_jwt = get_user(request)
if user_jwt.is_authenticated():
return user_jwt
token = request.META.get('HTTP_AUTHORIZATION', None)

user_jwt = AnonymousUser()
if token is not None:
try:
user_jwt = jwt.decode(
token,
settings.WP_JWT_TOKEN,
)
user_jwt = User.objects.get(
id=user_jwt['data']['user']['id']
)
except Exception as e: # NoQA
traceback.print_exc()
return user_jwt

还有一些注意事项,使用 LazySettings 代替设置始终是一个好习惯 Check this thread

这也是我的中间件订单
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'applications.custom_authentication.middleware.JWTAuthenticationMiddleware', # This is my middleware
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

请记住将您的自定义中间件放在 django.contrib.auth.middleware.AuthenticationMiddleware 之后中间件

关于python - 如何添加身份验证中间件 JWT django?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45266728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com