【问题标题】:Django REST and React - JWT Cookie not getting set in browser but working with postmanDjango REST 和 React - JWT Cookie 未在浏览器中设置但与邮递员一起使用
【发布时间】:2021-05-29 02:44:34
【问题描述】:

嘿,伙计们,我一直在尝试用 django set_cookie 解决问题,我在浏览器中找不到 cookie,它不起作用,但可以与邮递员一起使用。我浏览了一些 SO 答案,发现我必须在前端提供 withCredentials:true 并且我已经做到了,但它仍然不起作用。这是我的代码,有人可以告诉我其中的错误吗?

我想在登录时设置 cookie,到目前为止,我将令牌存储在本地存储中,我知道这不是一个安全的选择。

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
});

谢谢。

【问题讨论】:

  • Hey Danny..请告诉我你的 django 服务器 url 并用端口号反应 url。
  • 您好,感谢您的回复。 django server: http://127.0.0.1:8000/ 和反应 localhost:3000.

标签: reactjs django django-models django-rest-framework react-redux


【解决方案1】:

同一IP下设置后端和前端。前任。后端是

本地主机:8000

py manage.py runserver localhost:8000

前端是(默认):

本地主机:3000

不同的端口相同的IP

see this

【讨论】:

  • 谢谢。我去看看。
  • 终于成功了。非常感谢。干杯!
  • 使用这个:axios.defaults.headers.common['Authorization'] = Jwt ${token}
  • 好的。但你能告诉我它有什么不同吗?还是这是首选方式?谢谢
  • 它们之间没有任何区别,但这是为每个请求传递 JWT 令牌的最简单方法..
猜你喜欢
  • 2021-11-02
  • 2018-03-03
  • 2021-11-03
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2018-10-26
  • 2017-12-04
相关资源
最近更新 更多