Django oauth toolkit`或`

2024-05-14 15:40:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是drf和oauth toolkit,默认使用ISAuthenticatedTokenHasscope权限。我有一个包含作用域的视图 required_scopes = ['mod', 'admin']当用户登录到应用程序时,他拥有定义其权限范围的特殊组。因此,当主持人登录到应用程序时,他得到了mod范围。当他调用我的视图时,他得到403,因为AccessToken模型中的allow_scopes返回False。这是因为resource_scopes是['mod','admin'],提供的作用域是'mod'。当方法allow_scopes检查resource_scopes.issubset(provided_scopes)时,她返回False,这在我的情况下不是故意的

在不覆盖AccessToken模型中的allow_作用域的情况下,是否有其他选项来定义此视图需要作用域mod或作用域admin


Tags: 模型视图modfalse应用程序权限定义admin
1条回答
网友
1楼 · 发布于 2024-05-14 15:40:59

我想我找到了一个方法让它发挥作用。oauth2_provider没有提供任何函数来实现这一点。因此,我所做的是定义自己的自定义权限,它类似于TokenHasScope。因此,创建一个名为permissions.py的文件并粘贴代码

from rest_framework import permissions 
from django.core.exceptions import ImproperlyConfigured
from rest_framework.exceptions import PermissionDenied
from oauth2_provider.settings import oauth2_settings

class TokenHasAtLeastOneScope(permissions.BasePermission):
    """
    The request is authenticated as a user and the token used has at least one of the right scope
    """

    def has_permission(self, request, view):
        token = request.auth

        if not token:
            return False

        if hasattr(token, "scope"):  # OAuth 2
            required_scopes = self.get_scopes(request, view)
            log.debug("Required scopes to access resource: {0}".format(required_scopes))

            # If any scope in the list of required_scopes is valid, return True.
            for given_scope in required_scopes:
                if token.is_valid([given_scope]):
                    return True


            # Provide information about required scope?
            include_required_scope = (
                oauth2_settings.ERROR_RESPONSE_WITH_SCOPES
                and required_scopes
                and not token.is_expired()
                and not token.allow_scopes(required_scopes)
            )

            if include_required_scope:
                self.message = {
                    "detail": PermissionDenied.default_detail,
                    "required_scopes": list(required_scopes),
                }

            return False

        assert False, (
            "TokenHasAtLeastOneScope requires the"
            "`oauth2_provider.rest_framework.OAuth2Authentication` authentication "
            "class to be used."
        )

然后在视图中,导入权限并进行相应设置

permission_classes = (permissions.TokenHasAtLeastOneScope)
required_scopes = ['mod', 'admin']

在上面的自定义TokenHasAtLeastOneScope中,代码类似于TokenHasScope。唯一改变的是

for given_scope in required_scopes:
    if token.is_valid([given_scope]):
        return True

循环遍历required_scopes列表中的项,如果找到有效范围,则返回True

相关问题 更多 >

    热门问题