当前位置: 代码网 > it编程>前端脚本>Python > Django DRF Token认证基本使用小结

Django DRF Token认证基本使用小结

2025年12月08日 Python 我要评论
一. 前言django rest framework token是django rest framework中的一个扩展,用于实现用户认证和授权。它为每个用户生成一个唯一的token,并将其存储在数据

一. 前言

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认证内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com