django - Django Cookies 未在浏览器中设置但在邮递员中工作 - Django Rest Framework
问题描述
大家好,我在将 cookie 设置为浏览器时遇到问题。我已经使用 url http://xxxxxxxxx.herokuapp.com/将我的后端托管到 heroku并且我的前端在本地主机中。http://127.0.0.1:5501。如果我尝试使用在本地主机 127.0.0.1:8000 上运行的 django 登录,那么它可以正常工作并在浏览器中设置 cookie,但如果我尝试使用 heroku 之一,它不会在浏览器中设置 cookie,但如果尝试使用邮递员它工作正常。我无法弄清楚这个问题。我已经在我的后端添加了允许的来源。请帮我。
cors设置
ALLOWED_HOSTS = ['127.0.0.1','http://xxxxxxx.herokuapp.com']
CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN' #will be used in enforce_csrf or validating csrf token
ACCESS_CONTROL_ALLOW_HEADERS = True
CORS_ALLOW_HEADERS = ('content-disposition', 'accept-encoding',
'content-type', 'accept', 'origin','x-csrftoken')
# CORS_ORIGIN_ALLOW_ALL=True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
"http://127.0.0.1:5501",
"http://localhost:5501",
]
视图.py
class LoginView(APIView):
def post(self,request,format=None):
data = request.data
response = Response()
username = data.get('username', None)
password = data.get('password', None)
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
data = get_tokens_for_user(user)
response.set_cookie(
key = settings.SIMPLE_JWT['AUTH_COOKIE'],
value = data["access"],
expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'],
secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'],
httponly = settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'],
samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE']
)
response.set_cookie(
key = "tokenvalidate",
value = data["access"][0:len(data['access'])//2],
expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'],
secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'],
httponly = False,
samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE']
) #setting this for logout functionality. frontend can remove this non httponly cookie using js in logout function.
#if this cookie is not sent in request then the authorization will be failed.
csrf.get_token(request)
response.data = {"Success" : "Login successfully","data":data}
return response
else:
return Response({"No active" : "This account is not active!!"},status=status.HTTP_404_NOT_FOUND)
else:
return Response({"Invalid" : "Invalid username or password!!"},status=status.HTTP_404_NOT_FOUND)
验证.py
def enforce_csrf(request):
"""
Enforce CSRF validation.
"""
check = CSRFCheck()
# populates request.META['CSRF_COOKIE'], which is used in process_view()
check.process_request(request)
reason = check.process_view(request, None, (), {})
if reason:
# CSRF failed, bail with explicit error message
raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)
else:
return True
def validate_tokenvalidate(token,authtoken):
if token != str(authtoken)[0:len(str(authtoken))//2]:
raise exceptions.PermissionDenied('Invalid validate token sent')
class CustomJwtAuthentication(JWTAuthentication):
def authenticate(self, request):
header = self.get_header(request) #will check for the token in http_authorization header
if header is None:
raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE']) or None
tokenvalidate = request.COOKIES.get('tokenvalidate') or None
else:
raw_token = self.get_raw_token(header)
if raw_token is None or tokenvalidate is None:
return None #will return 401 status code
validated_token = self.get_validated_token(raw_token) #validate a jwt token
enforce_csrf(request) #will validate csrf token sent via x-csrftoken header
return self.get_user(validated_token), validated_token
解决方案
推荐阅读
- sql - 使用查询构建器根据条件对表中的同一列进行排序,具有不同的排序顺序
- android - 如何使 Firebase 数据库规则只允许 10 的增量
- asp.net-web-api - 使用 nhibernate orm 进行分布式缓存
- python - matplotlib get_color 用于子图
- android - React Native - 准确的当前位置(纬度,经度)
- php - 文件输入将字符串传递给控制器
- mysql - MySQL通过SQL文件创建表制作了奇怪的表结构
- java - 如何使用 Struts 将密码安全地传递给不同的应用程序
- javascript - 附加除第一个值之外的所有选项文本
- c# - C#如何确定foreach循环的最后一次迭代