client_credentials 模式下 Django-Rest-Framework 和 Django-Oauth-Toolkit 出现 403 错误

403 error with Django-Rest-Framework and Django-Oauth-Toolkit in client_credentials mode

我正在尝试使用 client_credentials 模式进行 Django-Oauth-Toolkit 身份验证,我可以:

  1. 创建成功创建我的client_idclient_secret
  2. 注册我的令牌

但之后,使用此令牌的任何 api 调用都会产生 403 错误消息:

{
    "detail": "You do not have permission to perform this action."
}

我的settings.py是:

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "oauth2_provider",
    "rest_framework",
    "drf_yasg",
    "users",
]

MIDDLEWARE = [
    "oauth2_provider.middleware.OAuth2TokenMiddleware",
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]



AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",},
    {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",},
    {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",},
]


REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "oauth2_provider.contrib.rest_framework.OAuth2Authentication",
        "rest_framework.authentication.SessionAuthentication",  # To keep the Browsable API
    ),
    "DEFAULT_PERMISSION_CLASSES": (
        "rest_framework.permissions.IsAuthenticated",
        "oauth2_provider.contrib.rest_framework.TokenHasReadWriteScope",
    ),
}

AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",  # To keep the Browsable API
    "oauth2_provider.backends.OAuth2Backend",
)

原来需要直接在视图中指定身份验证和权限,它们不会像 password 模式那样自动继承。

class MyView(APIView):

    authentication_classes = [OAuth2Authentication]
    permission_classes = [TokenHasReadWriteScope]