当前位置: 首页> 汽车> 报价 > Django REST Framework(十七)Authentication

Django REST Framework(十七)Authentication

时间:2025/7/10 8:16:56来源:https://blog.csdn.net/yjjpp2301/article/details/140812761 浏览次数: 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 CustomAuthenticationclass HomeAPIView(APIView):# authentication_classes = [CustomAuthentication, ]def get(self, request):"""单独设置认证方式"""print(request.user)  # 在中间件AuthenticationMiddleware中完成用户身份识别的,如果没有登录request.user值为AnonymousUserif 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 能够适应各种复杂的应用场景,从简单的基本认证到自定义的复杂认证逻辑。

关键字:Django REST Framework(十七)Authentication

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: