1

我正在尝试使用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",
)

4

1 回答 1

2

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

class MyView(APIView):

    authentication_classes = [OAuth2Authentication]
    permission_classes = [TokenHasReadWriteScope]

于 2020-04-29T20:48:15.243 回答