使用 django oauth 工具包的 Django rest 框架

Django rest framework working with django oauth toolkit

我正在使用 Django rest 框架创建 API,并且我正在添加 oauth2 身份验证。 我能够正确设置它,并且可以获得令牌来访问我的 API 端点。到目前为止一切都很好。

我现在的问题是如何在受保护的内容和受保护的内容方面更具选择性 public。在我的 API 中,有一个端点的子集,每个人都可以访问,因此他们是匿名用户,他们无法以相同的方式获取访问令牌,因为用户名和密码不存在。

这里是我的相关内容settings.py:

OAUTH2_PROVIDER = {
    # this is the list of available scopes
    'SCOPES': {
        'read': 'Read scope',
        'write': 'Write scope',
        'groups': 'Access to your groups'
    }
}

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.ext.rest_framework.OAuth2Authentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAdminUser',
    ),
    'PAGE_SIZE': 10
}
INSTALLED_APPS = (
    ...
    'oauth2_provider',
    'rest_framework',
    ...
)

views.py:

# Everything fine for this end point
class PrivateViewSet(viewsets.ModelViewSet):
    serializer_class = custom_serializers.MySerializer
    http_method_names = ['get', 'post', 'head', 'options']
    permission_classes = (permissions.IsAuthenticated, custom_permissions.IsAdminOrOwner, TokenHasReadWriteScope)

# Getting the error
class PublicViewSet(viewsets.ModelViewSet):
    serializer_class = custom_serializers.MyPublicSerializer
    permission_classes = (permissions.AllowAny,)

因此,当我尝试访问 "PublicViewSet" 端点时,出现以下错误:

{"detail": "Authentication credentials were not provided."}

有没有办法决定向哪些端点应用 oauth2 授权并保持其他端点开放 publicly?

您无法访问 PublicViewSet 端点,因为 它正在您提供的设置中寻找令牌 DEFAULT_AUTHENTICATION_CLASSES。它遵循 类。 为了避免在视图中出现这种情况,您需要传递一个空的 authentication_classes.

class PublicViewSet(viewsets.ModelViewSet):
    serializer_class = custom_serializers.MyPublicSerializer
    authentication_classes = ()
    permission_classes = (permissions.AllowAny,)