首页 > 解决方案 > 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

标签: djangocookiesdjango-rest-frameworkdjango-cors-headers

解决方案


推荐阅读