我想构建一个用户可以使用令牌进行身份验证的休息api。我在已安装的应用程序列表中包含了rest_framework.authtoken
。还增加了所需的配置在settings.py:如何使用django rest框架和ajax获取令牌
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='[email protected]' 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/%[email protected]%20password=secure123?_=1469883569618 405 (Method Not Allowed)
bundle.js:27453 Method Not Allowed
如何获得的令牌身份验证的用户,这样我可以用它来发布的经过认证的用户?
更新
我也是用django-cors-headers来处理有关问题CORS。
更新
%[email protected]%20password=secure123?_=1469885103431 405 xhr jquery-3.1.0.min.js:4 278 B 29 ms
更新:加入响应头
从浏览器的网络通信提供的详细信息,在Chrome中你会发现它在调试器的网络选项卡 – schacki
@schacki添加细节。请看一看。 –
%20表示空格,在你的ajax请求中用'?username'和'password'替换'username'为'&password'。另外我记得这也需要'&grant_type = password'参数。请求网址中不能有空格('')。 –