Django Rest Framework 令牌身份验证失败导致弹出

Django Rest Framework Token Authentication failure results in Pop up

我正在使用 django rest 框架令牌身份验证。如果我调用 url,提供一个无效或已删除的令牌 (Token aesdghfhkjdsajgaadsa),我会弹出一个询问用户名和密码的窗口。我怎样才能避免那个弹出窗口?我只需要回复

{"status": -1, "errors": "Token Expired"}

我正在使用给定的自定义令牌身份验证,

class ExpiringTokenAuthentication(TokenAuthentication):

def authenticate_credentials(self, key):
    try:
        token = self.model.objects.get(key=key)
    except self.model.DoesNotExist:
        raise exceptions.AuthenticationFailed('Invalid token')

    if not token.user.is_active:
        raise exceptions.AuthenticationFailed('User inactive or deleted')

    # This is required for the time comparison
    utc_now = datetime.utcnow()
    utc_now = utc_now.replace(tzinfo=pytz.utc)

    if token.created < utc_now - timedelta(hours=24):
        token.delete()
        raise exceptions.AuthenticationFailed('Token has expired')

    return token.user, token

有解决办法吗?

我假设弹出窗口是由 HTTP Basic/Digest 身份验证方案生成的 username/password?这很可能来自 BasicAuthentication 身份验证 class。

Django Rest Framework 将遍历 DEFAULT_AUTHENTICATION_CLASSES 中列出的身份验证方法,除非您在 APIView.authentication_classes.

中明确提供了一个列表

http://www.django-rest-framework.org/api-guide/authentication/#setting-the-authentication-scheme

我希望你想要这样的东西:

    def authenticate_credentials(self, key):
        resp = {}
        try:
            token = self.model.objects.get(key=key)
        except self.model.DoesNotExist:
            resp["status"] = -1
            resp["errors"] = "Invalid token"
            return resp

        if not token.user.is_active:
            resp["status"] = -1
            resp["errors"] = "User inactive or deleted"
            return resp

        # This is required for the time comparison
        utc_now = datetime.utcnow()
        utc_now = utc_now.replace(tzinfo=pytz.utc)

        if token.created < utc_now - timedelta(hours=24):
            token.delete()
            resp["status"] = -1
            resp["errors"] = "Token has expired"
            return resp

        return token.user, token