Django Tastypie POST Unauthorized on different servers

戏子无情 提交于 2019-12-11 20:43:16

问题


I have set up OAuth 2.0 as described by Ian Alexander using tastypie, django-oauth2-provider, and https://github.com/ianalexander/django-oauth2-tastypie/blob/master/src/authentication.py

This works splendidly on my local server

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()

When running this on our hosted development server, however, all POSTs come back HTTP/1.1 401 UNAUTHORIZED

I've attempted the following tests to no avail:

(1) replace

DjangoAuthorization() 

with

Authorization()

(2) replace

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

with

return True

(3) create a wrapper for all the api urls that is csrf exempt

The only things that has worked was to implement #1 and #2 at the same time (ie bypass authentication AND authorization) which seems to indicate it's not just a deny all at the webserver level.

Any thoughts here are appreciated!


回答1:


This happens because you have not enabled cors.

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()

Also in production or on any server: You need to add corsheaders to access it from other domains.

Use this django-cors-headers

Steps to use that :

  1. pip install django-cors-headers
  2. add 'corsheaders' in INSTALLED_APPS
  3. add 'corsheaders.middleware.CorsMiddleware' in MIDDLEWARE_CLASSES
  4. add CORS_ORIGIN_ALLOW_ALL = True in settings.py

P.S. : You can change the settings later after reading about cors to make it secure.




回答2:


It was an apache issue Add this line to your site conf file

WSGIPassAuthorization On

Where do I put "WSGIPassAuthorization On"?



来源:https://stackoverflow.com/questions/27134080/django-tastypie-post-unauthorized-on-different-servers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!