Search code examples
djangodjango-rest-frameworkpostmandjango-class-based-views

How to solve "detail": "Authentication credentials were not provided." error for Class-based APIView Django REST Framework?


I am using Django REST Framework and following this tutorial for retrieving all users when admin user is authenticated.

Class-based APIView of Django REST Framework

I am using Postman to test and trying to retrieve the list of all users registered in the system.

At first I try to use my "User Login with Token" API in Postman to create the necessary token as shown below:

User Login with Token

I copied the value of the "token" key and pasted it as the value of the "Authorization" key in the "Headers" section of "Get All Users" API in Postman as shown below. It is a GET request and I get the error "detail": "Authentication credentials were not provided." as the response.

Get All Users

Necessary code snippets are as follows:

views.py

class UserAccountListView(APIView):
"""
    List of All Users in the System / Application
    * Requires Token Authentication.
    * Only Admin Users are able to access this view.
"""
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAdminUser, )

def get(self, request, format=None):
    """
        Returns a List of All Users
    """
    full_names = [user.full_name for user in UsersAccount.objects.all()]
    return Response(full_names)

settings.py

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
        'rest_framework.permissions.IsAdminUser',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],

SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=30),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=1),
    "ROTATE_REFRESH_TOKENS": False,
    "BLACKLIST_AFTER_ROTATION": False,
    "UPDATE_LAST_LOGIN": True,

    "ALGORITHM": "HS256",
    "SIGNING_KEY": SECRET_KEY,
    "VERIFYING_KEY": None,
    "AUDIENCE": None,
    "ISSUER": None,

    "AUTH_HEADER_TYPES": ("Bearer", ),
    "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION",
    "USER_ID_FIELD": "id",
    "USER_ID_CLAIM": "user_id",

    "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken", ),
    "TOKEN_TYPE_CLAIM": "token_type",

    "JTI_CLAIM": "jti",

    "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp",
    "SLIDING_TOKEN_LIFETIME": timedelta(minutes=5),
    "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1),
}

urls.py

urlpatterns = [
    path('', UsersAccountAPIOverview.as_view()),
    path("all", UserAccountListView.as_view()),
    path("register", UsersAccountRegistrationView.as_view()),
    path("token", UserAccountTokenObtainPairView.as_view()),
    path("token/refresh", TokenRefreshView.as_view()),
    path("token/verify", TokenVerifyView.as_view()),
]

Looking forward for your kind support and help. If you need further information, I will provide you.

Thank you.


Solution

  • In your views.py remove the line:

    authentication_classes = (TokenAuthentication, )
    

    This is because in your settings.py file, the first line:

    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        ...
    ],
    

    mentions JWTAuthentication and not TokenAuthentication