Python 如何在 django-rest-framework 中为 API 使用 TokenAuthentication
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17560228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use TokenAuthentication for API in django-rest-framework
提问by Peter
I have a django project, using django-rest-framework to create api.
我有一个 django 项目,使用 django-rest-framework 创建 api。
Want to use token base authentication system so api call for (put, post, delete) will only execute for authorized user.
想要使用基于令牌的身份验证系统,因此 api 调用(放置、发布、删除)只会对授权用户执行。
I installed 'rest_framework.authtoken' and created token for each users.
我安装了“rest_framework.authtoken”并为每个用户创建了令牌。
So, now from django.contrib.auth.backends authenticate, it returns user, with auth_token as attribute. (when loged in successfully).
因此,现在从 django.contrib.auth.backends 进行身份验证,它返回用户,并将 auth_token 作为属性。(成功登录后)。
Now my question is how can I send the token with post request to my api and at api side how can I verify if token is valid and belongs to the correct user?
现在我的问题是如何将带有 post 请求的令牌发送到我的 api 以及在 api 端如何验证令牌是否有效并属于正确的用户?
Are there any methods in app rest_framework.authtoken to validate given user and its token? not found thisvery useful!
应用程序 rest_framework.authtoken 中是否有任何方法来验证给定的用户及其令牌?没发现这很有用!
Update (changes I made): Added this in my settings.py:
更新(我所做的更改):在我的 settings.py 中添加了这个:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
)
}
Also sending Token in my header but its still not working:
还在我的标头中发送 Token 但它仍然无法正常工作:
if new_form.is_valid:
payload= {"createNewUser":
{ "users": request.POST["newusers"],
"email": request.POST["newemail"]
}
}
headers = {'content-type' : 'application/json',
'Authorization': 'Token 6b929e47f278068fe6ac8235cda09707a3aa7ba1'}
r = requests.post('http://localhost:8000/api/v1.0/user_list',
data=json.dumps(payload),
headers=headers, verify=False)
采纳答案by Tom Christie
"how can I send the token with post request to my api"
“如何将带有 post 请求的令牌发送到我的 api”
From the docs...
从文档...
For clients to authenticate, the token key should be included in the Authorization HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings. For example:
对于客户端进行身份验证,令牌密钥应包含在授权 HTTP 标头中。键应该以字符串文字“Token”为前缀,用空格分隔两个字符串。例如:
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
"at api side how can I verify if token is valid and belongs to the correct user?"
“在 api 端,我如何验证令牌是否有效并属于正确的用户?”
You don't need to do anything, just access request.user
to return the authenticated user - REST framework will deal with returning a '401 Unauthorized' response to any incorrect authentication.
您不需要做任何事情,只需访问request.user
返回经过身份验证的用户 - REST framework 将处理对任何不正确的身份验证返回“401 Unauthorized”响应。
回答by Stefan Musarra
I finally have the django "rest-auth" package working for token authentication. If this helps, here is the client-side jQuery code that worked for me, after you successfully log in and receive the "auth_token":
我终于让 django “rest-auth” 包用于令牌身份验证。如果这有帮助,以下是在您成功登录并收到“auth_token”后对我有用的客户端 jQuery 代码:
var user_url = {API URL}/rest-auth/login
var auth_headers = {
Authorization: 'Token ' + auth_token
}
var user_ajax_obj = {
url : user_url,
dataType : 'json',
headers: auth_headers,
success : function(data) {
console.log('authorized user returned');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('error returned from ' + user_url);
}
};
$.ajax(
user_ajax_obj
);
回答by elke
To answer the first half of your question:
回答你问题的前半部分:
how can I send the token with post request to my api
如何将带有 post 请求的令牌发送到我的 api
You can use the Python requestslibrary. For the django-rest-framework TokenAuthentication, the token needs to be passed in the header and prefixed by the string Token
(see here):
您可以使用 Python请求库。对于 django-rest-framework TokenAuthentication,令牌需要在标头中传递并以字符串为前缀Token
(参见此处):
import requests
mytoken = "4652400bd6c3df8eaa360d26560ab59c81e0a164"
myurl = "http://localhost:8000/api/user_list"
# A get request (json example):
response = requests.get(myurl, headers={'Authorization': 'Token {}'.format(mytoken)})
data = response.json()
# A post request:
data = { < your post data >}
requests.post(myurl, data=data, headers={'Authorization': 'Token {}'.format(mytoken)})
回答by unlockme
If you are using coreapi. To add the Authorisation you do
import coreapi
auth = coreapi.auth.TokenAuthentication(scheme='Token', token=token_key)
Then you can do
client = coreapi.Client(auth=auth)
response = client.get(my_url)
如果您使用的是 coreapi. 添加授权你做
import coreapi
auth = coreapi.auth.TokenAuthentication(scheme='Token', token=token_key)
然后你可以做
client = coreapi.Client(auth=auth)
response = client.get(my_url)