我正在使用
rest_framework_simplejwt
在我的 Django 应用程序中实现 JWT 令牌加密。我创建了一个自定义中间件 TokenEncryptionMiddleware
,在将访问和刷新令牌设置为 cookie 之前对其进行加密。然而,客户端似乎收到了来自TokenObtainPairView
的未加密响应。
我在这里缺少什么?我需要注意
rest_framework_simplejwt
和自定义中间件之间是否存在任何交互,以确保我的加密按预期工作?
这是我的中间件代码:
"""
Middleware for crypting the JWT tokens before setting them as cookies.
"""
from base64 import urlsafe_b64encode
from cryptography.fernet import Fernet
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
class TokenEncryptionMiddleware(MiddlewareMixin):
"""
Middleware to encrypt the JWT tokens before setting them as cookies.
"""
def process_response(self, request, response):
"""
Encrypts the JWT tokens before setting them as cookies.
"""
if response.status_code == 200 and (
"access" in response.data and "refresh" in response.data
):
base_key = settings.JWT_KEY.encode()[:32]
cipher = Fernet(urlsafe_b64encode(base_key))
encrypted_access_token = cipher.encrypt(
response.data["access"].encode()
).decode()
encrypted_refresh_token = cipher.encrypt(
response.data["refresh"].encode()
).decode()
del response.data["access"]
del response.data["refresh"]
response.set_cookie(
"access_token",
encrypted_access_token,
httponly=True,
secure=True,
samesite="Strict",
)
response.set_cookie(
"refresh_token",
encrypted_refresh_token,
httponly=True,
secure=True,
samesite="Strict",
)
return response
中间件顺序
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"middlewares.crypter.TokenEncryptionMiddleware",
]
预期行为:
客户端应收到名为 access_token 和 refresh_token 的 cookie,其中包含加密的 JWT 令牌。
以类的形式创建自定义中间件需要一个神奇的方法。
class TokenEncryptionMiddleware(MiddlewareMixin):
"""
Middleware to encrypt the JWT tokens before setting them as cookies.
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
self.process_response(request, response)
return response
def process_response(self, request, response):
"""
Encrypts the JWT tokens before setting them as cookies.
"""
...
在django中间件中,根据请求、响应调用__call__magic方法。
您的 jwt 令牌加密过程预计会在响应中运行,因此我将其添加到 __call__magic 方法中。