一. 前言
django rest framework token是django rest framework中的一个扩展,用于实现用户认证和授权。它为每个用户生成一个唯一的token,并将其存储在数据库中。在用户进行api请求时,用户需要在请求的http header中包含token,这样服务器就可以验证用户的身份。
二. 基本使用
1. 安装drf token扩展:
pip install djangorestframework pip install django-rest-framework-authtoken
2.在django的settings.py中添加以下配置
installed_apps = [
...
'rest_framework',
'rest_framework.authtoken',
...
]
rest_framework = {
'default_authentication_classes': (
'rest_framework.authentication.tokenauthentication',
),
}
3. 迁移
python manage.py migrate
迁移完成会生成authtoken_token这张表来记录用户的token

4. 生成token
from rest_framework.authtoken.models import token from django.contrib.auth.models import user user = user.objects.create_user(username='johnson', password='doe') token, created = token.objects.get_or_create(user=user)
现在,johnson用户已经有了一个令牌。可以将此令牌返回给客户端,并在以后的请求中使用它进行身份验证:
get /api/test/ http/1.1 authorization: token <token>
5. 使用tokenauthentication
现在,可以通过在视图中使用tokenauthentication来保护视图
from rest_framework.authentication import tokenauthentication
from rest_framework.permissions import isauthenticated
from rest_framework.views import apiview
from rest_framework.response import response
class testview(apiview):
authentication_classes = [tokenauthentication]
permission_classes = [isauthenticated]
def get(self, request):
return response({'message': 'hello, world!'})
在这个例子中,testview视图被保护,只有经过身份验证的用户才能访问。
到此这篇关于django drftoken认证基本使用小结的文章就介绍到这了,更多相关django drftoken认证内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论