【问题标题】:Django Rest Framework HTTP Post Calls and Authentication with Ionic FrameworkDjango Rest Framework HTTP Post 调用和使用 Ionic 框架进行身份验证
【发布时间】:2017-12-05 13:33:22
【问题描述】:

我在我的 Django 项目中实现了 Django Rest Framework,因此我可以使用 Django 作为我的 Ionic Framework 应用程序的后端,同时维护我可以使用 Django 制作的 Web 应用程序。我使用 oauth 工具包完成了 OAuth2 的过程,但现在我不确定如何从 ionic 框架端进行 http 请求调用以验证用户并获取令牌。到目前为止,在 Ionic 方面,我的 http 请求为:

login(username, password, url) {
    let headers = new Headers()
    headers.append("Content-Type", "application/x-www-form-urlencoded");

    return this.http.post(url,
      {"username": username,
        "password": password,
      }, {headers: headers})
      .map(res => res.json());
  }

但是当我在浏览器中运行它时,我得到了No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 500.

在服务器端,curl 命令curl -X POST -d "grant_type=password&username=USERNAME&password=PASSWORD" -u "CLIENT ID:CLIENT SECRET" https://www.example.com/o/token/ 运行良好并返回一个令牌,其中 USERNAME、PASSWORD、CLIENT ID 和 CLIENT SECRET 都是各自的值。

我不确定这是否是正确的问题,但是如何将 cURL 命令转换为可以在 Ionic 应用程序中使用的东西?

这些是我的 Rest Framework 和 CORS 设置:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated'
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    ]
}

CORS_ORIGIN_WHITELIST = [
    'localhost:8100',
]

CORS_ALLOW_CREDENTIALS = True

【问题讨论】:

  • 我目前已经安装了,白名单包括“localhost:8100”
  • 嗯,如果您确定它已安装好(存在于中间件中,设置正确),不知道..
  • 我编辑了问题以包括我的 rest 框架和我的 settings.py 中的 cors 设置。这些设置是否正确?

标签: python django rest curl ionic-framework


【解决方案1】:

所以事实证明,如果您发送的请求的来源是localhost127.0.0.1,这是一样的,大多数浏览器都将来源发送为Null,所以最好添加CORS_ORIGIN_ALLOW_ALL = True到主Django项目的settings.py文件。

在那里,我收到关于 grant_type 无效的错误,所以在我的请求中我必须添加 "grant_type": "password",我还必须添加 "client_id": <your client id here>,其中 <your client id here> 是您的客户 ID没有<>

我还发现 Postman 是一个很棒的应用程序,可以帮助创建 api 并将 cURL 命令转换为有效的 HTTP 请求。

【讨论】:

    猜你喜欢
    • 2021-08-06
    • 2019-05-02
    • 2017-12-05
    • 1970-01-01
    • 2018-12-15
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    相关资源
    最近更新 更多