文章目录
- pip install djangorestframework pip install django-rest-framework-authtoken
- INSTALLED_APPS = [ … ‘rest_framework’, ‘rest_framework.authtoken’, … ] REST_FRAMEWORK = { ‘DEFAULT_AUTHENTICATION_CLASSES’: ( ‘rest_framework.authentication.TokenAuthentication’, ), }
- python manage.py migrate 迁移完成会生成authtoken_token这张表来记录用户的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>
- 现在,可以通过在视图中使用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认证内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客! 您可能感兴趣的文章: django restframework使用redis实现token认证 django基于存储在前端的token用户认证解析 Django JWT Token RestfulAPI用户认证详解
目录
- 一. 前言
- 二. 基本使用
- 1. 安装DRF Token扩展:
- 2.在Django的settings.py中添加以下配置
- 3. 迁移
- 4. 生成Token
- 5. 使用TokenAuthentication
Django Rest Framework Token是Django Rest Framework中的一个扩展,用于实现用户认证和授权。它为每个用户生成一个唯一的Token,并将其存储在数据库中。在用户进行API请求时,用户需要在请求的HTTP Header中包含Token,这样服务器就可以验证用户的身份。
pip install djangorestframework
pip install django-rest-framework-authtoken
INSTALLED_APPS = [
...
'rest_framework',
'rest_framework.authtoken',
...
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
}
python manage.py migrate
迁移完成会生成authtoken_token这张表来记录用户的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>
现在,可以通过在视图中使用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认证内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!
您可能感兴趣的文章:
- django restframework使用redis实现token认证
- django基于存储在前端的token用户认证解析
- Django JWT Token RestfulAPI用户认证详解