Django REST Framework(十七)Authentication

avatar
作者
猴君
阅读量:0

1.认证Authentication

在 Django REST framework (DRF) 中,可以在配置文件中配置全局默认的认证方案。常见的认证方式包括 cookie、session、和 token。DRF 提供了灵活的认证机制,可以在全局配置文件中设置默认认证方式,也可以在具体的视图类中设置单独的认证方式。

以下是默认的配置文件示例,位于

REST_FRAMEWORK = {      # 配置认证方式的选项      'DEFAULT_AUTHENTICATION_CLASSES':          (              'rest_framework.authentication.SessionAuthentication', # session认证              'rest_framework.authentication.BasicAuthentication', # 基本认证          )  }

可以在具体的视图类中通过设置 authentication_classes 类属性来设置单独的不同的认证方式。例如:

from rest_framework.authentication import SessionAuthentication, BasicAuthentication  from rest_framework.views import APIView  class ExampleView(APIView):      # 类属性      authentication_classes = [SessionAuthentication, BasicAuthentication]      def get(self, request):          pass

认证失败会有两种可能的返回值,这需要配合权限组件来使用:

  • 401 Unauthorized 未认证
  • 403 Permission Denied 权限被禁止

2.自定义认证

在一些特定场景中,可能需要自定义认证方式。以下是一个自定义认证的示例,位于 drfdemo.authentication 模块中:

from rest_framework.authentication import BaseAuthentication  from rest_framework.exceptions import APIException  class CustomAuthentication(BaseAuthentication):      """ 自定义认证方式 """      def authenticate(self, request):          print(":::")      """ 认证方法 request: 本次客户端发送过来的HTTP请求对象 """      token = request._request.META.get("HTTP_TOKEN")      if token != "123456789":          raise APIException("认证失败")      user = "root"      return (user, token) # 按照固定的返回格式填写(用户模型对象, None)

3.在视图中使用自定义认证

在视图中,可以通过设置 authentication_classes 类属性来使用自定义认证:

from django.contrib.auth.models import AnonymousUser from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authentication import SessionAuthentication from drfdemo.authentication import CustomAuthentication  class HomeAPIView(APIView):     # authentication_classes = [CustomAuthentication, ]     def get(self, request):         """单独设置认证方式"""         print(request.user)  # 在中间件AuthenticationMiddleware中完成用户身份识别的,如果没有登录request.user值为AnonymousUser         if request.user.id is None:             return Response("未登录用户:游客")         else:             return Response(f"已登录用户:{request.user}") 

当然,也可以注释掉视图中的配置,改成全局配置。以下是在 settings.py 中的配置示例:

"""drf配置信息必须全部写在REST_FRAMEWORK配置项中""" REST_FRAMEWORK = {     # 配置认证方式的选项【DRF的认证是内部循环遍历每一个注册的认证类,一旦认证通过识别到用户身份,则不会继续循环】     'DEFAULT_AUTHENTICATION_CLASSES': (         'drfdemo.authentication.CustomAuthentication',          # 自定义认证         'rest_framework.authentication.SessionAuthentication',  # session认证         'rest_framework.authentication.BasicAuthentication',    # 基本认证     ) } 

4.详细解释

  1. DEFAULT_AUTHENTICATION_CLASSES: 定义了认证类的列表,DRF 会按照顺序依次尝试每一个认证类。

    • CustomAuthentication: 自定义认证类,用于特定的认证需求。
    • SessionAuthentication: 使用 Django 的会话认证,适用于浏览器和持久会话。
    • BasicAuthentication: 使用 HTTP 基本认证,适用于简单的 API 认证。
  2. 视图中使用认证类: 可以在具体的视图类中通过设置 authentication_classes 类属性来覆盖全局设置,定义特定视图的认证方式。

  3. 认证失败的返回值:

    • 401 Unauthorized: 未认证。
    • 403 Permission Denied: 权限被禁止。

通过这些配置,您可以灵活地定制 DRF 的认证机制,以满足不同的需求。这种灵活性使得 DRF 能够适应各种复杂的应用场景,从简单的基本认证到自定义的复杂认证逻辑。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!