根据Django Rest Framework,当您要指定使用哪种身份验证时,可以在设置文件中将其设置为全局身份验证,例如
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
}
或按类查看 例如
@authentication_classes((SessionAuthentication, TokenAuthentication))
现在我似乎不明白的是,当我们在设置中将其指定为全局变量时,还必须将其作为每个类视图包含在内。
这是我的班级视图的代码
from django.http import HttpResponse
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.authentication import TokenAuthentication, SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
# Create your views here.
@api_view(['GET'])
@authentication_classes((SessionAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def index_view(request, format=None):
return Response([str(request.auth), str(request.user.password), str(request.session.username)])
这是我的settings.py文件中的代码
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated'
)
}
请希望我足够具体