简体   繁体   中英

DRF Token Authentication: { “detail”: “Authentication credentials were not provided.” }

I am working on a Django e-commerce project.

I tried to implement a token authentication system. I added rest_framework.authtoken to INSTALLED_APPS and

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (

        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

to settings file.

Here's my urls.py

    path('admin/', admin.site.urls),
    path('login_signup/',include('login_signup.urls')),
    path('profile',include('profile_info.urls')),
    path('',include('category.urls')),
    path('cart',include('cart.urls')),
    path('api_token_auth',views.obtain_auth_token,name='auth-token'),
]

Here's my category.urls file.


urlpatterns=[
path('category',CategoryView.as_view(),name='category'),
path('subcategory',SubcategoryView.as_view(),name='subcategory'),
path('product',ProductView.as_view(),name='product'),
path('search',SearchView.as_view(),name='search'),
]

I am able to obtain tokens by providing username and password at api_token_auth end point. 在此处输入图片说明

Now, I should be able to access any API provided I add Authorization HTTP header in this format. Authorization:Token "xyz"

But I keep getting {"detail":"Authentication credentials were not provided"} 在此处输入图片说明

Here is the view I am trying to access.


class SubcategoryView(APIView):
       def get(self,request):
           serializer=SubcategorySerializer(Subcategory.objects.all(),many=True)
           return JsonResponse({"subcategories":serializer.data})

Why do I keep getting this error? What am I doing wrong?

Remove the : from the Authorization header value . The value of the Authorization header should look like this:

Token <token value>

You need to pass the Token as Header like Authorization: Token 1740...20 . No semicolon after Token . Here is a curl command

curl -X GET http://127.0.0.1:8000/subcategory/ -H 'Authorization: Token 1740...20'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM