问题
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 :
- pip install django-cors-headers
- add 'corsheaders' in INSTALLED_APPS
- add 'corsheaders.middleware.CorsMiddleware' in MIDDLEWARE_CLASSES
- 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