我正在尝试在 Django 中应用 CSRF 令牌。
我正在使用中间件和自定义身份验证应用 csrf 令牌。
但我想我在做同样的过程两次。
因为cookie和response中csrf_token的值不一样
只通过中间件申请+检查csrf token可以吗?
中间件
settings.py
CSRF_COOKIE_SECURE = True # CSRF cookie enabled only Https server
CSRF_COOKIE_HTTPONLY = True # CSRF stored in http only cookie
CSRF_TESTED_ORIGINS = [
"http://localhost:8000"
]
CSRF_COOKIE_SAMESITE = "Lax" # Samesite "Lax" - Protection against csrf attacks
MIDDLEWARE = [
...
'django.middleware.csrf.CsrfViewMiddleware'
]
在身份验证期间强制执行 csrf
authenticate.py(我已将 CustomAuthentication 设置为 DEFAULT_AUTHENTICATION_CLASSES)
from rest_framework_simplejwt import authentication as jwt_authentication
from django.conf import settings
from rest_framework import authentication, exceptions as rest_exceptions
def enforce_csrf(request):
check = authentication.CSRFCheck(request)
reason = check.process_view(request, None, (), {})
print(check, reason)
print(request.META)
if reason:
raise rest_exceptions.PermissionDenied('CSRF Failed: %s' % reason)
class CustomAuthentication(jwt_authentication.JWTAuthentication):
def authenticate(self, request):
header = self.get_header(request)
if header is None:
raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE']) or None
else:
raw_token = self.get_raw_token(header)
if raw_token is None:
return None
validated_token = self.get_validated_token(raw_token)
enforce_csrf(request)
return self.get_user(validated_token), validated_token
登录查看
response["X-CSRFToken"] = request.COOKIES.get("csrftoken")
您可以在此处查看 django csrf 文档。 django 文档