【问题标题】:django built-in authentication system not working with reactdjango 内置身份验证系统不适用于反应
【发布时间】:2020-11-20 09:50:01
【问题描述】:

我正在构建一个 django-react 应用程序,使用 Django 呈现模板,用于 api 端点的 Django REST 框架,以及在 django 模板之上的 React。 我正在使用'rest_framework.authentication.SessionAuthentication',并且我已经实现了身份验证路由,但是 django 的内置身份验证方法(loginlogoutauthenticate)似乎只适用于 django 呈现的模板,而不适用于 React 组件。我的意思是如果我有这样的观点

def home_page(request, *args, **kwargs):
    print("local USER >>>", request.user)
    print("local SESSION >>>", request.session)
    return render(request, 'pages/homepage.html',
        {}, status=200)

我登录后访问路由,它会打印出usersession 对象。 但是对于 api 视图,

@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticatedOrReadOnly])
def post_list_view(request, *args, **kwargs):
    print("api USER >>>", request.user)
    print("api SESSION >>>", request.session)
    ...

即使我已登录,我也会收到 AnnonymousUserNone

当我检查浏览器 cookie 时,我发现了 csrftokensessionid cookie。 但是,如果我尝试发布请求,则会收到 403 Forbidden 错误,并显示“未提供身份验证凭据”。信息。 (我还将withCredentials 设置为true。)在请求标头中只有X-CSRFToken 标头(带有令牌),但缺少sessionid cookie。

在这一点上,我只是不知道下一步该做什么。我应该手动设置会话cookie吗?或者,我应该自定义内置方法吗? (如果是这样,请告诉我我该怎么做。) 我在这里做错了什么,我该如何解决?

编辑:

GET 请求的 xhr 标头:

POST 请求的

xhr 标头:

axios 配置:

const options = {
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'X-CSRFToken': csrftoken
    },
    withCredentials: true 
};

axios.post(url, data, options)
.then(response => {
    console.log(response);
    commentInput.current.value = '';
})
.catch(error => console.log(error));

【问题讨论】:

  • 你应该在每次向你的 Django 服务器发出请求时发送会话 cookie

标签: reactjs django authentication django-rest-framework


【解决方案1】:

原来我正在向localhost 发出请求,而对于some reason,您无法为其设置cookie。只需将url 更改为127.0.0.1 即可解决此问题。

【讨论】:

    【解决方案2】:

    设置withCredentials 应该适用于工作:

    axios.defaults.withCredentials = true
    

    你是这样设置的吗?

    如果没有帮助,您能否发布服务器响应标头、客户端请求标头和 axios 配置以及您如何发送请求(在客户端)的示例。

    一个问题,你为什么选择 Django 模板 + React?为什么不将 React 与 Django 分开?

    【讨论】:

    • 不,我没有以这种特定方式设置配置,但我确实将它作为参数传递。我使用 django 模板 + react 的原因是因为我必须使用 django-mptt 和它的模板标签来构建评论树,而我还没有找到用 react 实现它的方法......至少现在还没有。
    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 2021-08-23
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    相关资源
    最近更新 更多