【问题标题】:Custom Authorization class in Django TastypieDjango Tastypie 中的自定义授权类
【发布时间】:2016-06-08 19:13:49
【问题描述】:

我使用了以下自定义授权类

class CustomDjangoAuthorization(DjangoAuthorization):
    def read_detail(self, object_list, bundle):
        result = super(CustomDjangoAuthorization, self).read_detail(object_list, bundle)
        # now we check here for specific permission
        if bundle.request.user.profile.user_status:
            raise Unauthorized("You are not allowed to access that resource.")
        return result

它给了

401 未经授权

当user_status = 1。但是当我把user_status改成0时,它仍然显示

401 未经授权

错误。

我的未发送授权理解是,对于每个请求,tastepie 都会检查授权,并为 Ok 提供 200 响应,为 Unauthorized 提供 401 响应。我在这里遗漏了什么吗?

嘿 Sean,我尝试在 super 之前移动自定义代码。我得到一个

AttributeError: ‘AnonymousUser’对象没有属性‘profile’

在 localhost 中一切正常,生产出现问题。 这两种情况都会发生,user_status = 1 和user_status = 0

使用 Django 1.8 和 Tastypie 0.13.3。

【问题讨论】:

  • 很有可能您对 super() 的调用由于某些未连接的原因返回 401,然后您将其返回给用户。可能想检查结果中的结果:)
  • 啊,DjangoAuthorization 确实需要您登录,因此我认为是‘AnonymousUser’ object has no attribute ‘profile’ 错误。

标签: django tastypie


【解决方案1】:

@Sean Hayes 是对的,我的用户已注销。我正在使用自定义 url,但不知道默认情况下它没有采用我的 APIAuthentication。

我必须在我的自定义方法中添加 self.is_authenticated(request) 才能使其工作。

【讨论】:

    【解决方案2】:

    将调用前的自定义代码移至super(),并添加检查用户是否匿名:

    class CustomDjangoAuthorization(DjangoAuthorization):
       def read_detail(self, object_list, bundle):
        # check here for specific permission
        if (not bundle.request.user.is_authenticated()) or bundle.request.user.profile.user_status:
            raise Unauthorized("You are not allowed to access that resource.")
        result = super(CustomDjangoAuthorization, self).read_detail(object_list, bundle)
        return result
    

    您收到AttributeError: ‘AnonymousUser’ object has no attribute ‘profile’ 是因为您的用户已注销,所以request.user 是AnonymousUser,因此不是profile。

    【讨论】:

    • 我的用户没有退出。他已通过身份验证,因为我可以在我的请求中看到 API 密钥和用户名。当 user_status = 1 时,它不应该引发 Unauthorized。它在我的本地主机中工作正常,而不是在生产中。
    • 您的用户已退出,​​否则您将没有AnonymousUser。您可能正在发送身份验证数据,但显然您的服务器没有对它做任何事情。如果它在 dev 但不是 prod 中工作,则表明您的 prod 代码已过时或服务器配置错误。验证您的 auth 标头是否可以通过运行 Django 项目的任何进程。
    • 是的,你是对的,在我的回答中已经给出了解释。
    【解决方案3】:

    根据您的代码和症状,我猜您的授权详细信息不正确。检查您的username 和api_key。可能您有错字或您在生产中使用了本地授权详细信息。

    【讨论】:

    • 是的,我的网址没有通过身份验证。详情见我的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 2013-07-18
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多