繁体   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