具有有效凭据的 Django REST Framework 401 错误

问题描述 投票:0回答:1

我遇到一个问题,我向 api 端点发送 POST 请求

restaurant/api-token-auth
,并且我收到 json 响应的 401 错误:

{
    "detail": "Invalid token."
}

即使我在 POST 请求中发送了正确的凭据(用户名和密码),也会出现此响应。在这种情况下,我尝试了我的管理员帐户,它仍然给我这个响应。

这是我的 urls.py 代码(应用程序级别):

from django.urls import path
from . import views
from rest_framework.authtoken.views import obtain_auth_token

urlpatterns = [
    path('home/', views.index, name='index'),
    path('menu/', views.MenuItemView.as_view()),
    path('menu/<int:pk>', views.SingleMenuItemView.as_view()),
    path('api-token-auth/', obtain_auth_token)
    
]
    

urls.py(项目级别):

from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from restaurant.views import BookingViewSet

router = routers.DefaultRouter()
router.register(r'tables', BookingViewSet)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('restaurant/', include('restaurant.urls')),
    path('restaurant/booking/', include(router.urls)),
    path('auth/', include('djoser.urls')),
    path('auth/', include('djoser.urls.authtoken')),
]

设置.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'restaurant',
    'rest_framework',
    'rest_framework.authtoken',
    'djoser',
]

...(rest of code)

REST_FRAMEWORK = {

    'DEFAULT_RENDERER_CLASSES' : [

        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
        

    ],

    'DEFAULT_AUTHENTICATION_CLASSES' : [
        
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        

    ]


}


DJOSER = {"USER_ID_FIELD" : "username"}

我尝试使用管理面板并使用 djoser api 端点 auth/token/login 手动创建令牌,它可以工作,但这样不行。

django django-rest-framework
1个回答
0
投票

找到了解决方案,代码是正确的,只是我在 POST 请求中发送带有凭据的不记名令牌,而不是仅在 Insomnia 中发送凭据。

© www.soinside.com 2019 - 2024. All rights reserved.