DRF - 实现一个简单的 token 认证
rest framework 的 APIView 是继承 django 的 View,且有所扩展
代码:
from django.shortcuts import render, HttpResponse
from rest_framework.views import APIView # 要被视图函数所继承的
from rest_framework import exceptions # 异常处理
# 自己写的认证类,要继承 BaseAuthentication
class MyAuthentication(BaseAuthentication):
# 实例化对象要执行的方法
# 在 rf 的 request.py 的 _authenticate 函数中
def authenticate(self, request):
# 通过原生的 request 数据
token = request._request.GET.get("token")
# 去数据库中进行匹配
token = models.UserToken.objects.filter(token=token).first()
if not token:
raise exceptions.AuthenticationFailed("用户认证失败")
return ("admin", None) # 返回一个元组
def authenticate_header(self, request):
pass
class UsersView(APIView):
# 对象列表,遍历列表生成实例对象,用于认证
authentication_classes = [MyAuthentication, ]
def get(self, request, *args, **kwargs):
# request.user 的值是返回的元组中的第一个参数
# request.auth 的值是返回的元组中的第二个参数
print(request.user)
return HttpResponse("ok!")
要通过 MyAuthentication 的认证才能执行 UsersView 中的 get 函数
直接访问:

在 url 后面加一个 token 参数

Pycharm 中的执行结果:


浙公网安备 33010602011771号