如何在django-rest-framework中为API使用TokenAuthentication
我有一个django项目,使用django-rest-framework创建api。
想要使用基于令牌的身份验证系统,因此api调用(放置,发布,删除)将仅对授权用户执行。
我安装了“ rest_framework.authtoken”并为每个用户创建了令牌。
因此,现在从django.contrib.auth.backends进行身份验证,它以auth_token作为属性返回用户。(成功登录时)。
现在我的问题是如何将带有请求后的令牌发送到我的api,在api端如何验证令牌是否有效并属于正确的用户?
应用程序rest_framework.authtoken中是否有任何方法可以验证给定的用户及其令牌?没发现这很有用!
更新(我所做的更改):在我的settings.py中添加了此内容:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
)
}
还在我的标头中发送令牌,但仍无法正常工作:
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)