token认证
官方文档
https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
参照官方文档
设置INSTALLED_APPS
INSTALLED_APPS = [
...
'rest_framework.authtoken'
]
#设置rest_framework
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication'
#设置全局默认token认证
]
}
迁移数据库
python manage.py migrate
url.py
from rest_framework.authtoken import views
urlpatterns = [
···
url(r'^api-token-auth/', views.obtain_auth_token)
]
到postman请求
提示输入用户名 !前提已经创建超级用户
添加用户名密码
返回了token
{
"token": "230b857824c35f67c94be8da1b57cad00aca01ec"
}
views.py 创建一个需要认证的视图
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from django.http import JsonResponse
@api_view(['GET']) #get请求
@permission_classes([IsAuthenticated]) #需要认证
def t(request):
return JsonResponse({'code': 200})
请求这个url http://127.0.0.1:8000/t
{
"detail": "Authentication credentials were not provided."
}
#未提供身份验证凭据
也就是 需要token
token是请求http://127.0.0.1:8000/api-token-auth/ 返回的
添加了token 为什么还是不行??
查看具体头信息
对比官方 postaman 是Bearer 应该使用 Token
这里也要选择这个
添加一行Authorization 注意Token后面空格
请求成功