1. 程式人生 > >DRF 框架總結 - 認證 Authentication

DRF 框架總結 - 認證 Authentication

認證Authentication

可以在配置檔案中配置全域性預設的認證方案

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',   # 基本認證
        'rest_framework.authentication.SessionAuthentication',  # session認證
    )
}

也可以在每個檢視中通過設定 authentication_classess 屬性來設定

from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.views import APIView

class ExampleView(APIView):
    authentication_classes = (SessionAuthentication, BasicAuthentication)
    ...

認證失敗會有兩種可能的返回值:

  • 401 Unauthorized 未認證
  • 403 Permission Denied 許可權被禁止