Django Tastypie POST在不同服务器上未经授权

时间:2014-11-25 18:29:39

标签: python django oauth oauth-2.0 tastypie

我已经使用tastypie,django-oauth2-provider创建了Ian Alexander所描述的OAuth 2.0, https://github.com/ianalexander/django-oauth2-tastypie/blob/master/src/authentication.py

这在我的本地服务器上非常有效

class AllowGetAuthentication(OAuth20Authentication):
    def is_authenticated(self, request, **kwargs):
        """ If GET, don't check auth, otherwise fall back to parent """
        if request.method == "GET":
            return True
        else:
            return super(AllowGetAuthentication, self).is_authenticated(request, **kwargs)

class BaseModelResource(ModelResource):
    class Meta:
        allowed_methods = ['get', 'post']
        always_return_data = True
        authentication = AllowGetAuthentication()
        authorization = DjangoAuthorization()

但是,当我们在托管开发服务器上运行时,所有POST都会返回HTTP / 1.1 401 UNAUTHORIZED

我尝试过以下测试无济于事:

(1)替换

DjangoAuthorization() 

Authorization()

(2)替换

return super(AllowGetAuthentication, self).is_authenticated(request, **kwargs)

return True

(3)为csrf豁免的所有api url创建一个包装器

唯一有效的方法是同时实现#1和#2(即绕过身份验证和授权),这似乎表明它不仅仅是在网络服务器级别的拒绝。

此处的任何想法都表示赞赏!

2 个答案:

答案 0 :(得分:0)

这是因为你没有启用角色。

class BaseModelResource(ModelResource):
     class Meta:
        queryset = BaseModel.objects.all()
        resource_name = 'api'
        authorization = DjangoAuthorization()
        detail_allowed_methods = ['get', 'post']
        always_return_data = True
        authentication = OAuth20Authentication()

同样在制作中或在任何服务器上:您需要添加corsheaders以从其他域访问它。

使用此django-cors-headers

使用它的步骤:

  1. pip install django-cors-headers
  2. 添加' corsheaders'在INSTALLED_APPS
  3. 添加' corsheaders.middleware.CorsMiddleware'在MIDDLEWARE_CLASSES
  4. 在settings.py
  5. 中添加CORS_ORIGIN_ALLOW_ALL = True

    P.S。 :您可以在阅读有关cors之后更改设置以使其安全。

答案 1 :(得分:0)

这是一个apache问题 将此行添加到您的网站配置文件

WSGIPassAuthorization On

Where do I put "WSGIPassAuthorization On"?