我正在使用Django OAuth工具包来限制对API的访问,并且我遵循了this tutorial,但是由于某些原因,DOT限制了对我对此请求的每个请求的访问。
urls.py
:
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from api import views
router = routers.DefaultRouter()
admin.autodiscover()
from rest_framework import generics, permissions, serializers
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/carfax/$', views.GetCarFax.as_view({'get': 'list'}), name='list'),
url(r'^api/v1/get_carfax/(?P<pk>[\w-]+)/$', views.GetCarFax.as_view({'get': 'retrieve'}), name='retrieve'),
url(r'^api/v1/carfax/create/$', views.PostCarFax.as_view({'post': 'create'}), name='create'),
url('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
]
views.py:
class GetCarFax(viewsets.ModelViewSet):
''' This view will be used for POSTing new carfax reports to the database '''
queryset = CarFax.objects.all()
serializer_class = CarFaxSerializer
# authentication_classes = []
permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope, TokenHasScope]
#print('TEST')
# lookup_field = "vin"
def list(self, request):
# accessed at url: ^api/v1/carfax/$
queryset = CarFax.objects.all()
serializer = CarFaxSerializer(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None, *args, **kwargs):
# accessed at url: ^api/v1/retrieve/{pk}/$
queryset = CarFax.objects.all()
record = get_list_or_404(queryset, vin__exact=pk)
serializer = CarFaxSerializer(record, many=True)
return Response(serializer.data)
class PostCarFax(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
queryset = CarFax.objects.all()
serializer_class = CarFaxSerializer
我的requests
文件:
headers = {
'Authorization': 'Bearer *****'
}
data = {
"vin": test[0],
"structural_damage": test[2],
"total_loss": test[1],
"accident": test[5],
"airbags": 'TESTTTTT',
"odometer": test[4],
"recalls": test[6]
}
data = json.dumps(data)
response = requests.post('http://127.0.0.1:8000/api/v1/carfax/create/', data=data, headers=headers, cookies=cookies)
print(response.status_code)
return response
get-token.py
:
def authorize():
client_id = '***'
client_secret = '***'
data = {
'grant_type': 'password',
'username': 'test1',
'password': 'test1',
}
response = requests.post('http://localhost:8000/o/token/', data=data, auth=(client_id, client_secret))
return response.text
我不确定我在哪里出问题了,删除身份验证后请求可以正常工作。但否则,它始终会引发403禁止错误。我成功获取了令牌,基本上是403错误,告诉我令牌没有授予我这些权限