2

我正在使用 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

有解决方案吗?

4

2 回答 2

2

我假设弹出窗口是由 HTTP Basic/Digest 身份验证方案生成的用户名/密码?这很可能来自 BasicAuthentication 身份验证类。

除非您在 APIView.authentication_classes 中明确提供了列表,否则 Django Rest Framework 将遍历 DEFAULT_AUTHENTICATION_CLASSES 中列出的身份验证方法。

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

于 2015-04-29T12:21:10.317 回答
-1

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

    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
于 2015-04-29T12:52:35.470 回答