欢迎访问宙启技术站
智能推送

rest_framework.settings.api_settings的DEFAULT_AUTHENTICATION_CLASSES默认验证类设置

发布时间:2023-12-19 01:19:52

rest_framework.settings.api_settings中的DEFAULT_AUTHENTICATION_CLASSES是Django REST framework中默认的身份验证类。该设置用于指定用于身份验证的类的顺序列表。

例如,如果我们想要使用认证令牌(Token Authentication)来验证API请求,可以设置DEFAULT_AUTHENTICATION_CLASSES如下:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        # 其他身份验证类
    ]
}

上面的设置将首先尝试使用TokenAuthentication进行身份验证,如果请求中包含有效的令牌,请求将被授权。如果没有有效的令牌,则会继续尝试其他身份验证类。

下面是一个完整的例子,展示如何使用TokenAuthentication验证API请求:

1. 首先,我们需要安装以下依赖包:

pip install djangorestframework
pip install django-rest-framework-simplejwt

2. 在Django的settings.py文件中添加以下配置:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
}

上面的配置中,我们指定了TokenAuthentication类作为首选的身份验证类,并指定了SessionAuthentication和BasicAuthentication作为备选的身份验证类。DEFAULT_PERMISSION_CLASSES设置了默认的权限类,要求请求必须经过身份验证。

3. 创建一个API视图,并进行身份验证:

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated

from rest_framework_simplejwt.authentication import JWTAuthentication

class ExampleView(APIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        content = {'message': 'Hello, World!'}
        return Response(content)

上面的例子中,我们创建了一个名为ExampleView的API视图。我们在视图的authentication_classes属性中指定了JWTAuthentication类,表示我们要使用认证令牌(Token Authentication)对此API视图进行身份验证。我们还指定了permission_classes属性为IsAuthenticated,表示只有已经经过身份验证的用户才可以访问该视图。

4. 配置URL路由:

from django.urls import path

from .views import ExampleView

urlpatterns = [
    path('example/', ExampleView.as_view(), name='example'),
]

上面的例子中,我们将ExampleView视图映射到/example/路径。

现在,我们可以使用认证令牌向服务器发送请求来测试我们的API。例如,可以使用curl命令来发送GET请求:

curl -H "Authorization: Token YOUR_TOKEN" http://localhost:8000/example/

上面的请求将通过TokenAuthentication进行身份验证,并返回一个包含消息"Hello, World!"的JSON响应。

总结:

通过设置rest_framework.settings.api_settings中的DEFAULT_AUTHENTICATION_CLASSES,可以配置Django REST framework中的默认身份验证类。我们可以根据需求选择不同的身份验证类,比如TokenAuthentication、SessionAuthentication和BasicAuthentication等,并将其作为API视图的authentication_classes属性的值。这样,在接收到API请求时,就会自动使用配置的身份验证类对请求进行身份验证。