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

Posted

技术标签:

【中文标题】client_credentials 模式下 Django-Rest-Framework 和 Django-Oauth-Toolkit 出现 403 错误【英文标题】:403 error with Django-Rest-Framework and Django-Oauth-Toolkit in client_credentials mode 【发布时间】:2020-08-14 02:04:46 【问题描述】:

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

    创建成功创建我的client_idclient_secret 注册我的令牌

但之后,使用此令牌的任何 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",
)

【问题讨论】:

【参考方案1】:

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

class MyView(APIView):

    authentication_classes = [OAuth2Authentication]
    permission_classes = [TokenHasReadWriteScope]

【讨论】:

以上是关于client_credentials 模式下 Django-Rest-Framework 和 Django-Oauth-Toolkit 出现 403 错误的主要内容,如果未能解决你的问题,请参考以下文章

帮助有趣的项目:复活节彩蛋 jQuery DJ [关闭]

歌曲怎么改成DJ版

谁知道2009最新的DJ舞曲啊

DJ软件 XYLIO Future DJ Pro v1.5.2.0 MacOSX

spring security client_credentials grant_type - 支持刷新令牌

带有 client_credentials 的 Spring Oauth2 不验证用户