为什么视图集的权限没有被覆盖?

问题描述 投票:0回答:1

我已经创建了一个用于身份验证的视图集。由于这是身份验证视图集,因此我希望未经授权的用户也可以访问此视图集。根据 DRF 文档,这就是我所拥有的:

class AuthenticationViewSet(viewsets.ViewSet):
    permission_classes = [AllowAny]

    def create_user(self, request: Request) -> Response:
        #code for creating a user

由于我希望其他视图集只能由授权用户访问,因此我在 settings.py 中设置了以下内容:

REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "authentication.token_auth.ExpiringTokenAuthentication"
    ]
}

当我对 create_user 端点进行 API 调用时,收到一条错误消息:“未找到令牌”。 为什么会发生这种情况?难道不应该根据视图集中的permission_classes列表来覆盖权限吗?

供参考,我的身份验证类:

class ExpiringTokenAuthentication(TokenAuthentication):
    def authenticate(self, request):
        if COOKIE_KEY in request.COOKIES:
            token_key = request.COOKIES[COOKIE_KEY]
        else:
            raise exceptions.AuthenticationFailed("No token found")

        try:
            token = Token.objects.get(key=token_key)
        except Token.DoesNotExist:
            return exceptions.AuthenticationFailed("Invalid token")

        if isTokenExpired(token):
            raise exceptions.AuthenticationFailed("Token has expired")

        user = token.user

        return (user, token)


def isTokenExpired(token):
    currentTime = datetime.now(datetime.UTC)
    currentTimeUTC = currentTime.replace(tzinfo=pytz.UTC)
    return token.created < currentTimeUTC - timedelta(hours=TOKEN_EXPIRE_HOURS)

django django-rest-framework django-rest-framework-permissions
1个回答
0
投票

我花了比应该花的时间更长的时间来解决这个问题。但是,如果您想允许不受限制地访问视图集,则必须在视图集中添加

permission_classes=[]
authentication_classes=[]

身份验证和权限是DRF中的两个不同的概念。身份验证是为了弄清楚用户是谁。权限是确定是否允许经过身份验证的用户执行请求的操作。

在这种情况下,当我通过设置

permission_classes=[]
绕过权限时,我仍然收到 401,因为请求不是来自经过身份验证的用户,因为 DRF 正在检查请求以确定是谁在发出请求。

因此视图集的代码变为:

class AuthenticationViewSet(viewsets.ViewSet):
    permission_classes = []
    authentication_classes = []

    def create_user(self, request: Request) -> Response:
        # code for creating a user

© www.soinside.com 2019 - 2024. All rights reserved.