[英]Authentication credentials were not provided drf
当我试图访问api时,我收到此错误:
"detail": "Authentication credentials were not provided."
我已将其包含在settings.py中:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES':(
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES':(
'rest_framework.permissions.IsAuthenticated',
)
}
我的app api urls.py:
from django.urls import path,include
from . import views
from rest_framework import routers
router = routers.SimpleRouter()
router.register(r'',views.UserViewSet, 'user_list')
urlpatterns = router.urls
我的views.py:
class UserViewSet(viewsets.ModelViewSet):
queryset = User.object.all()
serializer_class = serializers.UserSerializers
serializers.py:
from rest_framework import serializers
from users.models import User
class UserSerializers(serializers.ModelSerializer):
class Meta:
model = User
fields = ('email','password')
我的主要urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('',include(urls)),
path ('', include(user_urls)),
path('api/',include(api_urls)),
当我运行localhost:8000 / api我收到错误
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES':(
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES':(
'rest_framework.permissions.IsAuthenticated',
)
}
在settings.py
文件中使用它,发生的事情是rest_framework.authentication.TokenAuthentication
需要一个带有令牌的授权标头作为它的值,但你无法通过浏览器发送,要从浏览器浏览API,你必须启用SessionAuthentication
。
如果使用TokenAuthentication,则无法从浏览器URL访问api。 正如@DarkOrb所说, TokenAuthentication需要一个带有令牌的授权标头作为它的值。 因此,无论何时调用api,都必须传递令牌 。 你可以用邮递员测试你的api。
在上面的图像中,我已经在邮递员的标题中传递了令牌来访问我的api。 当您从前端呼叫您的api时,请将您的令牌与请求一起传递。 如果您只想在桌面浏览器中使用api,那么您只能使用SessionAuthentication。对于移动设备,必须完成Tokenauthentication 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.