Python Django Rest Framework - 未提供身份验证凭据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26906630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django Rest Framework - Authentication credentials were not provided
提问by Marcos Aguayo
I'm developing an API using Django Rest Framework. I'm trying to list or create an "Order" object, but when i'm trying to access the console gives me this error:
我正在使用 Django Rest Framework 开发 API。我正在尝试列出或创建一个“订单”对象,但是当我尝试访问控制台时出现此错误:
{"detail": "Authentication credentials were not provided."}
Views:
意见:
from django.shortcuts import render
from rest_framework import viewsets
from django.contrib.auth.models import User
from rest_framework.renderers import JSONRenderer, YAMLRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from order.models import *
from API.serializers import *
from rest_framework.permissions import IsAuthenticated
class OrderViewSet(viewsets.ModelViewSet):
model = Order
serializer_class = OrderSerializer
permission_classes = (IsAuthenticated,)
Serializer:
序列化器:
class OrderSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Order
fields = ('field1', 'field2')
And my URLs:
还有我的网址:
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
from django.utils.functional import curry
from django.views.defaults import *
from rest_framework import routers
from API.views import *
admin.autodiscover()
handler500 = "web.views.server_error"
handler404 = "web.views.page_not_found_error"
router = routers.DefaultRouter()
router.register(r'orders', OrdersViewSet)
urlpatterns = patterns('',
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token'),
url(r'^api/', include(router.urls)),
)
And then I'm using this command in the console:
然后我在控制台中使用这个命令:
curl -X GET http://127.0.0.1:8000/api/orders/ -H 'Authorization: Token 12383dcb52d627eabd39e7e88501e96a2sadc55'
And the error say:
错误说:
{"detail": "Authentication credentials were not provided."}
采纳答案by Marcos Aguayo
Solved by adding "DEFAULT_AUTHENTICATION_CLASSES" to my settings.py
通过将“DEFAULT_AUTHENTICATION_CLASSES”添加到我的 settings.py 中解决
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAdminUser'
),
}
回答by sherelock
Just for other people landing up here with same error, this issue can arise if your request.useris AnonymousUserand not the right user who is actually authorized to access the URL. You can see that by printing value of request.user. If it is indeed an anonymous user, these steps might help:
只是对于登陆这里的其他人遇到同样的错误,如果您request.user是AnonymousUser而不是实际有权访问 URL 的正确用户,则可能会出现此问题。您可以通过打印request.user. 如果确实是匿名用户,这些步骤可能会有所帮助:
Make sure you have
'rest_framework.authtoken'inINSTALLED_APPSin yoursettings.py.Make sure you have this somewhere in
settings.py:REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', # ... ), # ... }Make sure you have the correct token for the user who is logged in. If you do not have the token, learn how to get it here. Basically, you need to do a
POSTrequest to a view which gives you the token if you provide the correct username and password. Example:curl -X POST -d "user=Pepe&password=aaaa" http://localhost:8000/Make sure the view which you are trying to access, has these:
class some_fancy_example_view(ModelViewSet): """ not compulsary it has to be 'ModelViewSet' this can be anything like APIview etc, depending on your requirements. """ permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication,) # ...Use
curlnow this way:curl -X (your_request_method) -H "Authorization: Token <your_token>" <your_url>
请确保您有
'rest_framework.authtoken'在INSTALLED_APPS你的settings.py。确保你在某处有这个
settings.py:REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', # ... ), # ... }确保您拥有登录用户的正确令牌。如果您没有令牌,请在此处了解如何获取。基本上,
POST如果您提供正确的用户名和密码,您需要向视图发出请求,该视图为您提供令牌。例子:curl -X POST -d "user=Pepe&password=aaaa" http://localhost:8000/确保您尝试访问的视图具有以下内容:
class some_fancy_example_view(ModelViewSet): """ not compulsary it has to be 'ModelViewSet' this can be anything like APIview etc, depending on your requirements. """ permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication,) # ...curl现在这样使用:curl -X (your_request_method) -H "Authorization: Token <your_token>" <your_url>
Example:
例子:
curl -X GET http://127.0.0.1:8001/expenses/ -H "Authorization: Token 9463b437afdd3f34b8ec66acda4b192a815a15a8"
回答by Robert Kovac
If you are runnig Django on Apache using mod_wsgi you have to add
如果您使用 mod_wsgi 在 Apache 上运行 Django,则必须添加
WSGIPassAuthorization On
in your httpd.conf. Otherwise authorization header will be stripped out by mod_wsgi.
在您的 httpd.conf 中。否则授权头将被 mod_wsgi 剥离。
回答by uestcfei
This help me out without "DEFAULT_PERMISSION_CLASSES" in my settings.py
这有助于我在 settings.py 中没有“DEFAULT_PERMISSION_CLASSES”
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'PAGE_SIZE': 10
}
回答by lukeaus
If you are playing around in the command line (using curl, or HTTPie etc) you can use BasicAuthentication to test/user your API
如果您在命令行中玩弄(使用 curl 或 HTTPie 等),您可以使用 BasicAuthentication 来测试/使用您的 API
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication', # enables simple command line authentication
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
)
}
You can then use curl
然后你可以使用curl
curl --user user:password -X POST http://example.com/path/ --data "some_field=some data"
or httpie(its easier on the eyes):
或httpie(它更容易在眼睛上):
http -a user:password POST http://example.com/path/ some_field="some data"
or something else like Advanced Rest Client (ARC)
回答by Pritam Roy
Adding SessionAuthentication in settings.py will do the job REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
),
}
在 settings.py 中添加 SessionAuthentication 将完成这项工作 REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
),
}
回答by prashant
I too faced the same since I missed adding
由于我错过了添加,我也面临同样的问题
authentication_classes = (TokenAuthentication)
authentication_classes = (TokenAuthentication)
in my API view class.
在我的 API 视图类中。
class ServiceList(generics.ListCreateAPIView):
authentication_classes = (SessionAuthentication, BasicAuthentication, TokenAuthentication)
queryset = Service.objects.all()
serializer_class = ServiceSerializer
permission_classes = (IsAdminOrReadOnly,)
In addition to the above, we need to explicitly tell Django about the Authenticationin settings.py file.
除了上述之外,我们还需要在 settings.py 文件中明确告诉 Django身份验证。
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}
回答by Aishwarya kabadi
Since it is session Login so you need to provide you credentials
so do
127.0.0:8000/adminadmin and login later it will work fine
由于它是会话登录,因此您需要提供凭据,因此请127.0.0:8000/admin稍后进行
管理员和登录,它会正常工作

