簡體   English   中英

Django REST 和 React - JWT Cookie 未在瀏覽器中設置,但與 Z03D476861AFD3841510F2 一起使用

[英]Django REST and React - JWT Cookie not getting set in browser but working with postman

嘿伙計們,我一直試圖用 django set_cookie解決問題,我在瀏覽器中找不到 cookie,它不起作用,但適用於 postman。 我瀏覽了一些 SO 答案,發現我必須在前端提供withCredentials:true並且我已經做到了,但它仍然不起作用。 這是我的代碼,有人可以告訴我其中的錯誤嗎?

我想在登錄時設置 cookies,到目前為止,我將令牌存儲在本地存儲中,我知道這不是一個安全的選擇。

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']
            )
            csrf.get_token(request)
            response.data = {"Response": "Login Successful", "data":data,}
            return response
        else:
            return Response({"error": "User is not active"}, status=status.HTTP_404_NOT_FOUND)
    else:
        return Response({"error": "Invalid credentials"}, status=status.HTTP_404_NOT_FOUND)

反應前端

const handleSubmit = (e) => {
    e.preventDefault();
    axiosInstance
        .post(url, {
            username: formData.username,
            password: formData.password,
        })
       // .then((res) => {
       //     localStorage.setItem('access_token', res.data.access);
       //     localStorage.setItem('refresh_token', res.data.refresh);
        //    })
        .then(()=> {
            history.push('/');
            window.location.reload(); 
        })
};

axiosInstance

const axiosInstance = axios.create({
baseURL: baseURL,
timeout: 5000,
headers: {
    // Authorization: localStorage.getItem('access_token')
    //     ? 'JWT ' + localStorage.getItem('access_token')
    //     : null,
    'Content-Type': 'application/json',
    accept: 'application/json',

},
withCredentials: true
});

謝謝你。

相同的 IP下設置后端和前端。 前任。 后端是

本地主機:8000

py manage.py runserver localhost:8000

前端是(默認情況下):

本地主機:3000

不同端口相同 Ip

看到這個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM