【问题标题】:Django Rest Interface - unable to access authenticated user in my resourceDjango Rest 接口 - 无法访问我的资源中经过身份验证的用户
【发布时间】:2012-03-05 01:23:20
【问题描述】:

我正在使用 django-rest-interface 来构建 API。但是,当我通过 curl 发出请求时,说:

    curl -u 'username:password' -X PUT --data "field=value" http://127.0.0.1:8080/resource/

并尝试在资源中的 get()、post()、put() 或 delete() 方法中访问 request.user,我总是收到一条错误消息,提示我正在访问 AnonymousUser()。

如何对这些方法进行身份验证?

编辑:

我可以通过在 django-rest-framework 的文件 views.py 的函数 dispatch() 中添加 request.user=self.user 来解决这个问题,就在 handler(request, *args, * *夸克)。

但是,我不确定这是否正确。

【问题讨论】:

    标签: python django authentication rest interface


    【解决方案1】:
    from djangorestframework.authentication import BasicAuthentication
    
    class BasicUserAuthentication(BasicAuthentication):
       """ A simple wrapper that also sets request.user when using basic auth """
    
    def authenticate(self, request):
        user = super(BasicUserAuthentication, self).authenticate(request)
        if user:
            request.user = user
        return user
    

    处理这个问题的一种更简洁的方法是继承 BasicAuthentication,如上所述。虽然正是这样的事情让我质疑 django-rest-framework...

    【讨论】:

      猜你喜欢
      • 2016-01-15
      • 2012-05-16
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      相关资源
      最近更新 更多