【问题标题】:Django Rest Framework Token Authentication failure results in Pop upDjango Rest Framework Token Authentication 失败导致弹出
【发布时间】:2015-07-08 16:16:33
【问题描述】:

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

有解决办法吗?

【问题讨论】:

    标签: python django django-rest-framework http-token-authentication


    【解决方案1】:

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

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

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

    【讨论】:

    • 那是正确的。我不得不更改我的 DEFAULT_AUTHENTICATION_CLASSES 列表。当我从列表中删除 BasicAuthentication 时,我得到了解决方案。谢谢
    【解决方案2】:

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

        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
    

    【讨论】:

      猜你喜欢
      • 2014-11-21
      • 2020-01-16
      • 2016-03-06
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2021-11-27
      • 2018-02-10
      相关资源
      最近更新 更多