关于rest_framework.settings.api_settings中DEFAULT_AUTHENTICATION_CLASSES的默认认证类
在rest_framework.settings.api_settings中,DEFAULT_AUTHENTICATION_CLASSES 是Django REST Framework(DRF)中用于用户认证的默认认证类。该设置定义了将会被用于全局身份验证的认证类列表。
DRF提供了多种身份验证方式来确保用户的安全性和数据保护。DEFAULT_AUTHENTICATION_CLASSES中的认证类列表将按照顺序进行尝试,直到找到一个认证类可以成功验证身份或权限。
下面是一些DEFAULT_AUTHENTICATION_CLASSES中常见的默认认证类及其使用示例:
1. TokenAuthentication
TokenAuthentication是DRF提供的最常见的身份验证类之一,它基于用户提供的令牌(token)进行身份验证。在该认证类中,每个用户都被赋予一个 的令牌,然后将该令牌用于每个请求的Authorization header中。
使用TokenAuthentication的示例代码如下:
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, authentication_classes, permission_classes
@api_view(['GET'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
def api_view_example(request):
# 执行相应操作
return Response("Authenticated user only")
上述示例中,我们使用@api_view装饰器将视图函数标记为DRF视图,并使用@authentication_classes和@permission_classes装饰器将TokenAuthentication和IsAuthenticated应用到该视图函数上。这样,只有提供有效令牌的用户才能访问该视图。
2. SessionAuthentication
SessionAuthentication是DRF提供的另一种常见的身份验证类,它基于Django的Session机制进行身份验证。当用户通过登录页面登录并获取到session id后,可以在其他请求中使用该session id进行身份验证。
使用SessionAuthentication的示例代码如下:
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, authentication_classes, permission_classes
@api_view(['GET'])
@authentication_classes([SessionAuthentication])
@permission_classes([IsAuthenticated])
def api_view_example(request):
# 执行相应操作
return Response("Authenticated user only")
在示例中,我们使用@api_view装饰器将视图函数标记为DRF视图,并使用@authentication_classes和@permission_classes装饰器将SessionAuthentication和IsAuthenticated应用到该视图函数上。这样,只有通过登录获取有效session id的用户才能访问该视图。
3. JWTAuthentication
JWTAuthentication 是使用JWT(JSON Web Token)进行身份验证的认证类。JWT是一种跨域身份验证机制,它通过将用户的身份信息加密在一个token中,然后将其发送给服务器进行身份验证。
使用JWTAuthentication的示例代码如下:
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, authentication_classes, permission_classes
@api_view(['GET'])
@authentication_classes([JSONWebTokenAuthentication])
@permission_classes([IsAuthenticated])
def api_view_example(request):
# 执行相应操作
return Response("Authenticated user only")
在示例中,我们导入的是JWTAuthentication而不是TokenAuthentication。这是因为JWTAuthentication实际上是DRF第三方库rest_framework_jwt中的一个认证类。我们使用相同的装饰器将JWTAuthentication和IsAuthenticated应用到该视图函数上。
上述介绍的是DEFAULT_AUTHENTICATION_CLASSES中的一些常见认证类及其使用示例。除了这些默认的认证类,你还可以自定义认证类来满足你的特定需求。
