设置认证的方案 与 限制对未登录用户的访问
1)使用全局配置
默认使用的是SessionAuthentication
REST_FRAMEWORK = {'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework.authentication.SessionAuthentication','rest_framework.authentication.BasicAuthentication',)}
2)使用装饰器
函数视图使用装饰器
@api_view(['GET'])@authentication_classes((SessionAuthentication, BasicAuthentication))@permission_classes((IsAuthenticated,))def example_view(request, format=None):content = {'user': unicode(request.user), # `django.contrib.auth.User` 实例。'auth': unicode(request.auth), # None}return Response(content)
3)使用基于类的视图
from rest_framework.authentication import SessionAuthentication, BasicAuthenticationfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.response import Responsefrom rest_framework.views import APIViewclass ExampleView(APIView):authentication_classes = (SessionAuthentication, BasicAuthentication)permission_classes = (IsAuthenticated,)def get(self, request, format=None):content = {'user': unicode(request.user), # `django.contrib.auth.User` 实例。'auth': unicode(request.auth), # None}return Response(content)
未认证和禁止的响应
当未经身份验证的请求被拒绝时,有下面两种不同的错误代码可使用,与身份验证方案一一对应
HTTP 401 未认证(对应,BasicAuthentication)
HTTP 403 无权限(默认使用,对应SessionAuthentication)

Session认证
需要保证在请求中包含有效的CSRF Token
https://docs.djangoproject.com/zh-hans/4.0/ref/csrf/
相关文档
https://q1mi.github.io/Django-REST-framework-documentation/api-guide/authentication_zh/
