【问题标题】:Angular 2 Django-Rest-Framework Authentication with http.postAngular 2 Django-Rest-Framework 身份验证与 http.post
【发布时间】:2017-02-28 05:05:03
【问题描述】:

我花了比我想承认的更多的时间来找到这个问题的答案,但我自己似乎无法弄清楚。 我在this tutorial 之后有一个 Django-rest-api,可以使用 httpie 或 curl 与 api 通信并传递凭据。我还有一个 angular 2 SPA,它可以发送 http.get 请求并从服务器取回数据。一切正常,直到我尝试使用 POST 并从 angular 2 应用程序中传递身份验证数据,导致 Http 403(禁止)。

由于 api 可以很好地与 curl 配合使用,这让我觉得我在以角度发送 http.post 时做错了。这是我的代码:

postStuff() {
    var body = "username=myusername&password=mypassword";
    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http.post('http://localhost:8000/rest/', body, { headers: headers })
        .map(res => res.json());
}

这是一个运行良好的 curl 示例:

curl -H 'Accept: application/json; indent=4' -u myusername:mypassword http://127.0.0.1:8000/rest/

我需要在标头中包含“授权”标头吗?我尝试了 Authorization:Basic 但没有运气。我还运行了一个 curl 以找到允许的选项并且允许 POST。 我基本上想要我的 http.post 中 curl 中的“-u 用户名:密码”(或 http.get,如果可能的话)的等效项

还值得一提的是,在不需要身份验证的 api 部分,我使用 POST 得到 400(错误请求),而 GET 工作正常。 例如,这很好用:

return this.http.get('http://127.0.0.1:8000/users/')
        .map(res => res.json())

但事实并非如此:

return this.http.post('http://127.0.0.1:8000/users/', { headers: headers })
        .map(res => res.json());

【问题讨论】:

    标签: curl angular http-headers django-rest-framework


    【解决方案1】:

    需要解决两个问题:

    1 - 在角度方面,将 withCredentials 属性设置为 true:

    return this.http.post('http://127.0.0.1:8000/users/', 
    { headers: headers, withCredentials: true })
        .map(res => res.json());
    

    2- 在 Django 端处理 CSRF 和访问源: 这些和 CORS 是它们自己的蠕虫罐,在堆栈溢出的许多其他问题中得到解决。

    【讨论】:

      猜你喜欢
      • 2019-01-01
      • 1970-01-01
      • 2013-05-03
      • 2021-09-09
      • 2015-11-12
      • 2019-01-18
      • 2015-12-26
      • 2020-04-10
      • 2015-06-01
      相关资源
      最近更新 更多