DRF - 全局认证
在 app 目录下创建 utils 目录,并创建 auth.py
auth.py:
from rest_framework.authentication import BaseAuthentication # 用于全局认证 class GlobalAuthentication(BaseAuthentication): def authenticate(self, request): return ("Admin", "admin") def authenticate_header(self, request): pass # 用于局部认证 class MyAuthentication(BaseAuthentication): def authenticate(self, request): return ("Test", "test") def authenticate_header(self, request): pass
在 settings.py 中设置全局认证:
REST_FRAMEWORK = { # 全局使用的认证类 "DEFAULT_AUTHENTICATION_CLASSES": ["drf.utils.auth.GlobalAuthentication", ], }
这里用的是认证类的路径
views.py:
from django.http import JsonResponse from rest_framework.views import APIView # 订单信息 ORDER_DICT = { 1: { "commodity": "Phone", "price": 3600, "date": "2021-01-03", }, 2: { "commodity": "Computer", "price": 6700, "date": "2021-01-05", }, } class OrderView(APIView): """ 查看订单 """ def get(self, request, *args, **kwargs): print(request.user) print(request.auth) response = {"code": 1000, "msg": None, "data": None} try: response["data"] = ORDER_DICT except Exception as e: pass return JsonResponse(response)
运行结果
打印的内容:
说明现在用的是全局认证类 GlobalAuthentication
要是不想用全局认证,而想用局部认证,则可以用 authentication_classes 进行覆盖
views.py:
from django.http import JsonResponse from rest_framework.views import APIView from drf.utils.auth import MyAuthentication ORDER_DICT = { 1: { "commodity": "Phone", "price": 3600, "date": "2021-01-03", }, 2: { "commodity": "Computer", "price": 6700, "date": "2021-01-05", }, } class OrderView(APIView): """ 查看订单 """ # 设置局部认证类,覆盖全局认证类 authentication_classes = [MyAuthentication, ] def get(self, request, *args, **kwargs): print(request.user) print(request.auth) response = {"code": 1000, "msg": None, "data": None} try: response["data"] = ORDER_DICT except Exception as e: pass return JsonResponse(response)
打印结果:
如果既不想用全局认证,也不想用局部认证,则可以使用 authentication_classes = [] 来进行置空