Django Tastypie POST Unauthorized on different ser

2019-08-24 08:35发布

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!

2条回答
疯言疯语
2楼-- · 2019-08-24 09:13

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.

查看更多
放我归山
3楼-- · 2019-08-24 09:15

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

WSGIPassAuthorization On

Where do I put "WSGIPassAuthorization On"?

查看更多
登录 后发表回答