1. 设置认证方案

设置认证方案有三种:

  • 设置全局认证方案;
  • 在每个类视图或者视图集类的基础上设置身份认证方案;
  • 在视图函数的基础上设置认证方案。

    1.1 全局认证

    在配置文件**setting.py**中配置默认的全局认证方案:
    1. REST_FRAMEWORK = {
    2. 'DEFAULT_AUTHENTICATION_CLASSES': (
    3. 'rest_framework.authentication.BasicAuthentication', # 基本认证
    4. 'rest_framework.authentication.SessionAuthentication', # session认证
    5. )
    6. }

    1.2 基于视图函数认证

    1. @api_view(['GET'])
    2. @authentication_classes([SessionAuthentication, BasicAuthentication])
    3. @permission_classes([IsAuthenticated])
    4. def example_view(request, format=None):
    5. content = {
    6. 'user': str(request.user), # `django.contrib.auth.User` instance.
    7. 'auth': str(request.auth), # None
    8. }
    9. return Response(content)

    1.3 基于类视图、视图集的身份认证

    ```python from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView

class ExampleView(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated]

  1. def get(self, request, format=None):
  2. content = {
  3. 'user': str(request.user), # `django.contrib.auth.User` instance.
  4. 'auth': str(request.auth), # None
  5. }
  6. return Response(content)

```