简体   繁体   中英

Django Tastypie POST Unauthorized on different servers

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!

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

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

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

WSGIPassAuthorization On

Where do I put "WSGIPassAuthorization On"?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM