我已成功设置TokenAuthentication
并生成了用户在验证时成功接收的令牌。不幸的是,我无法在没有错误的情况下将令牌发送到API(DRF TokenAuthentication)。该令牌是硬编码的,用于测试并使用djangos runserver
运行。我从回复中看到只允许POST
和OPTIONS
,但我可以curl
没有任何问题:
curl -X GET http://127.0.0.1:8000/api-token-auth -H 'Authorization: Token a83ff8dabb7fc7b800d381fd3994dfe2051cc0c2'
实施
控制器/ Login.js:
reSignInCommand: function (aToken) {
var me = this;
Ext.Ajax.request({
url: 'http://127.0.0.1:8000/api-token-auth/',
method: 'GET',
disableCaching: false,
timeout: 10000,
useDefaultXhrHeader: false,
headers: {
'Authorization' : 'Token a83ff8dabb7fc7b800d381fd3994dfe2051cc0c2'
},
success: function(response) {
console.log("success");
},
failure: function(response) {
console.log("failure");
}
});
API / urls.py:
from django.conf.urls import patterns, url, include
urlpatterns += patterns('',
url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token'),
)
调试:
Request URL:http://127.0.0.1:8000/api-token-auth/
Request Method:GET
Status Code:405 METHOD NOT ALLOWED
Request headers:
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:da,zh;q=0.8,de;q=0.6,en;q=0.4
Authorization:Token a83ff8dabb7fc7b800d381fd3994dfe2051cc0c2
Cache-Control:no-cache
Connection:keep-alive
Host:127.0.0.1:8000
Origin:http://127.0.0.1
Pragma:no-cache
Referer:http://127.0.0.1/sencha/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
Response headers:
HTTP/1.0 405 METHOD NOT ALLOWED
Date: Fri, 20 Dec 2013 10:19:50 GMT
Server: WSGIServer/0.1 Python/2.7.5
Vary: Accept, Cookie
Access-Control-Allow-Origin: *
Content-Type: application/json
X-Frame-Options: SAMEORIGIN
Allow: POST, OPTIONS
答案 0 :(得分:4)
curl
响应与AJAX响应相同。 curl
响应返回301状态代码而不是405,因为您使用了不同的URL(没有尾部斜杠)。
问题是您只能发布到/api-token-auth/
网址, GET 方法未实施。
正如Django REST框架API token authentication docs所说,用例是这样的:
username
和password
发送到/api-token-auth/
- 才能获得身份验证令牌。在进行权限和限制检查之前,以及允许任何其他代码继续执行之前,始终在视图的最开始运行身份验证。
您无需验证令牌,因为它已为您完成。如果HTTP头中提供的令牌是有效请求,则会有额外的对象: