【发布时间】:2016-12-05 01:59:24
【问题描述】:
我想构建一个rest api,用户可以在其中使用令牌进行身份验证。我已将rest_framework.authtoken 包含在已安装的应用程序列表中。还在settings.py中添加了所需的配置:
INSTALLED_APPS = (
...
'rest_framework.authtoken'
)
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
}
定义了一种方法来监听post_save 信号并为新创建的用户创建新令牌。然后我做了迁移。创建新用户后,我可以看到该用户的令牌。
如果我这样做了
http POST 0.0.0.0:80/api-token-auth/ username='user@gmail.com' password='secure123'
我收到了回复
HTTP/1.0 200 OK
Allow: POST, OPTIONS
Content-Type: application/json
Date: Sat, 30 Jul 2016 12:05:30 GMT
Server: WSGIServer/0.1 Python/2.7.3
Vary: Cookie
X-Frame-Options: SAMEORIGIN
{
"token": "4aecfb249265064c55300d782e4c7e66b8b77063"
}
所以我想它的工作原理。但如果我尝试使用 ajax 登录:
$.ajax({
url: 'http://test.com/api-token-auth/ username=' + email + ' password='+ password,
dataType: 'json',
cache: false,
success: function(data) {
console.log(data);
}.bind(this),
error: function(xhr, status, err) {
console.log(err);
}.bind(this)
});
我在浏览器控制台中收到此错误:
jquery-3.1.0.min.js:4 GET http://test.com/api-token-auth/%20username=user@gmail.com%20password=secure123?_=1469883569618 405(不允许的方法)
bundle.js:27453 方法不允许
如何获取经过身份验证的用户的令牌,以便我可以使用它作为经过身份验证的用户发布?
更新
我也在使用django-cors-headers 来处理与 CORS 相关的问题。
更新
%20username=user@gmail.com%20password=secure123?_=1469885103431 405 xhr jquery-3.1.0.min.js:4 278 B 29 ms
更新:添加响应标头
【问题讨论】:
-
提供浏览器网络通信的详细信息,在 Chrome 中,您可以在调试器的网络选项卡中找到它
-
@shacki 添加了详细信息。请看一看。
-
%20 表示空格,在您的 ajax 请求中,将 'username' 替换为 '?username' 和 'password' 到 '&password'。我还记得这也需要 '&grant_type=password' 参数。请求 url 中不能有空格 (' ')。
标签: python ajax django rest django-rest-framework