0
点赞
收藏
分享

微信扫一扫

【doxygen】markdown 表格中插入换行与缩进

往复随安_5bb5 2023-07-02 阅读 67
djangopython

一. 前言

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视图被保护,只有经过身份验证的用户才能访问。

以上就是关于DRF - 【Token】认证基本使用, 希望对你有所帮助!

举报

相关推荐

0 条评论