执行命令:
python3 manage.py drf_create_token auth_user
异常描述:
CommandError: Cannot create the Token: user user does not exist
实施令牌认证
我们需要在settings.py模块中添加两条信息。首先将rest_framework.authtoken包含到您的文件中,INSTALLED_APPS
并包含TokenAuthentication
to REST_FRAMEWORK
:
myapi / settings.py
INSTALLED_APPS = [
# Django Apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third-Party Apps
'rest_framework',
'rest_framework.authtoken', # <-- Here
# Local Apps (Your project's apps)
'myapi.core',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication', # <-- And here
],
}
迁移数据库以创建将存储认证令牌的表:
python manage.py migrate
现在我们需要一个用户帐户。让我们使用manage.py
命令行实用程序创建一个:
python manage.py createsuperuser --username vitor --email vitor@example.com
仅出于测试目的,生成令牌的最简单方法是再次使用命令行实用程序:
python manage.py drf_create_token vitor
这条信息,随机字符串9054f7aa9305e012b3c2300408c3dfdf390fcddf
是我们接下来要用来进行身份验证的字符串。
但是,既然我们已经准备TokenAuthentication
就绪,让我们尝试向/hello/
端点发出另一个请求:
http http://127.0.0.1:8000/hello/
请注意,我们的API现在如何根据所需的身份验证方法向客户端提供一些额外的信息。
所以最后,让我们使用我们的令牌!
http http://127.0.0.1:8000/hello/ 'Authorization: Token 9054f7aa9305e012b3c2300408c3dfdf390fcddf'
就是这样。现在,在所有后续请求中,您都应包含header Authorization: Token 9054f7aa9305e012b3c2300408c3dfdf390fcddf
。
格式看起来很怪异,通常在如何设置此标头方面存在混淆。这将取决于客户端以及如何设置HTTP请求标头。
例如,如果我们使用的是cURL,则命令将如下所示:
curl http://127.0.0.1:8000/hello/ -H 'Authorization: Token 9054f7aa9305e012b3c2300408c3dfdf390fcddf'
或者,如果是Python请求调用:
import requests
url = 'http://127.0.0.1:8000/hello/'
headers = {'Authorization': 'Token 9054f7aa9305e012b3c2300408c3dfdf390fcddf'}
r = requests.get(url, headers=headers)
用户请求令牌
DRF为用户提供了一个端点,以便用户使用其用户名和密码来请求身份验证令牌。
包括以下到达urls.py模块的路由:
myapi / urls.py
from django.urls import path
from rest_framework.authtoken.views import obtain_auth_token # <-- Here
from myapi.core import views
urlpatterns = [
path('hello/', views.HelloView.as_view(), name='hello'),
path('api-token-auth/', obtain_auth_token, name='api_token_auth'), # <-- And here
]
因此,现在我们有了一个全新的API端点,即/api-token-auth/
。让我们先检查一下:
http http://127.0.0.1:8000/api-token-auth/
它不处理GET请求。基本上,这只是一个接收带有用户名和密码的POST请求的视图。
让我们再试一次:
http post http://127.0.0.1:8000/api-token-auth/ username=vitor password=123
响应主体是与此特定用户关联的令牌。此后,您将存储此令牌并将其应用于将来的请求。
然后,再次向API发出POST请求的方式取决于您使用的语言/框架。
https://stackoverflow.com/questions/53628570/token-authentication-with-django-rest-framework